↻one more pass.
Arrays & hashing · Easy

Two Sum: the idea to remember.

Return the indices of two values that add up to a target in an unsorted array.

Solve on LeetCode ↗

The core insight

Check whether the complement is already in a map before storing the current value.

Why it works

Before index i, the map contains only earlier indices. A matching complement therefore cannot reuse i.

The mistake to avoid

Inserting first can pair an element with itself, for example [3] with target 6.

Time: O(n) expectedSpace: O(n)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> seen = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int need = target - nums[i];
        // Check first: the map must contain only earlier indices.
        if (seen.containsKey(need)) return new int[]{seen.get(need), i};
        seen.put(nums[i], i);
    }
    throw new IllegalArgumentException("No valid pair");
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.