← Back to libraryQuestion 85 of 273
⌨️Java CodingIntermediate

Two Sum — Find Pairs with a Target Sum

📌 Definition:

Given an array and a target, find two numbers that add up to the target (return their indices or the pair).

📖 Detailed Explanation:

Brute force checks every pair — O(n^2). The optimal one-pass approach keeps a hash map of value -> index; for each element x, check whether (target - x) has already been seen. O(n) time, O(n) space. Clarify whether indices or values are required and how duplicates are handled.

💻 Solutions:
public static int[] twoSum(int[] a, int target) {
    Map<Integer,Integer> seen = new HashMap<>();
    for (int i = 0; i < a.length; i++) {
        int need = target - a[i];
        if (seen.containsKey(need)) return new int[]{seen.get(need), i};
        seen.put(a[i], i);
    }
    return new int[]{-1, -1};
}
function twoSum(a, target) {
  const seen = new Map();
  for (let i = 0; i < a.length; i++) {
    const need = target - a[i];
    if (seen.has(need)) return [seen.get(need), i];
    seen.set(a[i], i);
  }
  return [-1, -1];
}
def two_sum(a, target):
    seen = {}
    for i, x in enumerate(a):
        if target - x in seen:
            return [seen[target - x], i]
        seen[x] = i
    return [-1, -1]
🔑 Key Points:
  • Hash map of value -> index
  • For each x look up complement target - x
  • One pass, O(n) beats O(n^2)
  • Clarify indices vs values, duplicates
🌍 Real-World Example:

The complement trick — "have I already seen the value that completes this?" — reconciles debits/credits and matches request/response pairs.

🎯 Scenario-Based Interview Question:

A candidate gives the nested-loop O(n^2) solution. What is the key idea for O(n)?