Skip to content

Two Sum

Return the positions of the two numbers that add up to a target, in one pass with a hash map.

EasyHashing
Solve on LeetCode

The problem

You get an array of integers nums and an integer target. Exactly one pair of positions holds two numbers that add up to target. Return those two indices in any order, and don't use the same position twice.

Input nums = [8, 3, 11, 6], target = 9

Output [1, 3]

nums[1] + nums[3] = 3 + 6 = 9.

Input nums = [-2, 7, -2, 4], target = -4

Output [0, 2]

The two -2s sit at different positions, so together they count as a pair.

Key constraint: The array can hold up to 10,000 numbers. Checking every pair means about 50 million checks, while one pass with a map needs about 10,000 steps.

How to spot the pattern

  • You need two items whose values combine to a known total.
  • You must return positions, and sorting the array would scramble them.
  • A fast "have I seen this value already?" check would finish the job.

The idea

For each number x, the partner it needs is target - x. If you remember every number you have already walked past, along with its index, you can check for that partner instantly. A hash map gives you that instant lookup, so a single walk through the array is enough.

Brute force: Check every pair with two nested loops, which takes O(n^2) time.

Step by step

  1. 1Create an empty map from a number to the index where you saw it.
  2. 2Walk through the array and, for each number, work out need = target - number.
  3. 3If need is already in the map, return its index together with the current index.
  4. 4Otherwise store the current number with its index and move on.

See the pattern move

The hashing pattern on a small example. Step through it, or press play.

Code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        seen = {}  # value -> index where we saw it
        for i, num in enumerate(nums):
            need = target - num
            if need in seen:
                return [seen[need], i]
            seen[num] = i
        return []

Complexity

Time

O(n)

Space

O(n)

Each number is looked up once and stored once; the map holds at most n entries.

Watch out for

  • Storing the number before checking for its partner, which can pair a number with itself (5 with target 10 when there is only one 5).
  • Sorting the array first: the sorted positions are not the indices you have to return.

Follow-up questions

What if the array is already sorted?

Use two pointers that start at both ends and move inward, which needs only O(1) extra space. That is Two Sum II.

What if many pairs can add up to the target and you must count them?

Store how many times each number has appeared so far, and add that count every time its partner shows up.

In Hinglish

Har number par socho: isko kaunsa partner chahiye? Woh pehle dikh chuka hai toh map turant bata dega, warna is number ko uske index ke saath map mein daal do.

Related problems