150NeetCode 150

3.Two Sum

EasyBlind 75Arrays & Hashing ยท 3/9
LeetCode #1Video

Problem

Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target.

Exactly one valid pair is guaranteed to exist, and you may not use the same element twice (the two indices must be different). The answer can be returned in any order.

Examples

Input:  nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9.
Input:  nums = [3, 2, 4], target = 6
Output: [1, 2]
Explanation: 2 + 4 = 6. Index 0 (value 3) cannot be paired with itself.
Input:  nums = [3, 3], target = 6
Output: [0, 1]

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Exactly one valid answer exists.

๐Ÿ’ก Key Insight

For each number x, the only partner that works is its complement target - x. Instead of searching the array for the complement every time, remember every value seen so far in a HashMap<value, index>. Then "does the complement exist to my left?" becomes an O(1) lookup, and one pass finds the pair.

Brute Force

TimeO(nยฒ)SpaceO(1)

Intuition

Try every pair of distinct indices (i, j) and return the first one whose values sum to target.

Algorithm

  1. For i from 0 to n - 1:
  2. For j from i + 1 to n - 1:
  3. If nums[i] + nums[j] == target, return [i, j].
  4. (Unreachable given the guarantee) return an empty array.

Visualization

nums = [3, 2, 4], target = 6

i=0 (3): 3+2=5 โœ—, 3+4=7 โœ—
i=1 (2): 2+4=6 โœ“ โ†’ return [1, 2]

Code

java
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) { // j > i, so an element is never paired with itself
                if (nums[i] + nums[j] == target) {
                    return new int[] {i, j};
                }
            }
        }
        return new int[0];
    }
}

Complexity

  • Time: O(nยฒ) โ€” every pair is examined in the worst case.
  • Space: O(1) โ€” only loop indices.

Complexity Comparison

Approach Time Space
Brute Force O(nยฒ) O(1)
Sorting + Two Pointers O(n log n) O(n)
One-Pass Hash Map O(n) O(n)

Common Pitfalls

  • Inserting nums[i] into the map before checking โ€” with nums = [3, ...], target = 6 you would return [0, 0].
  • Sorting nums directly and returning the sorted positions โ€” the problem asks for the original indices.
  • Duplicates like [3, 3]: a two-pass map that first inserts everything overwrites the first 3's index; the one-pass version handles it naturally.
  • Returning the values instead of the indices.