Two Sum solution explained

The Two Sum solution that interviewers expect is a single pass with a hash map: for each number, check whether the value that would complete the target has already been seen, and if not, record the current number and its index. That turns an O(n²) pair search into O(n) time with O(n) extra memory.

By Published 7 min read

The problem in plain words

You receive a list of whole numbers and one more number called the target. Somewhere in the list, two entries at different positions add up to exactly the target. Return those two positions. You can assume there is one such pair, and you may not pair an entry with itself. The order of the two positions in your answer usually does not matter, but ask.

Small examples, written for this page
ListTargetAnswer (indexes)Why
[4, 9, 1, 7]8[2, 3]1 + 7 = 8
[6, 6]12[0, 1]Two equal values at different positions are allowed
[-3, 10, 5, 13]10[0, 3]Negative numbers work the same way: -3 + 13 = 10
[2, 8, 0, 5]5[2, 3]Zero is an ordinary value: 0 + 5 = 5
Small examples, written for this page. Scroll sideways on a small screen.

Before planning anything, ask a few questions. Can the list be empty or have one element? What should happen if no pair exists: return an empty list, return null, or raise an error? Are the values bounded? Is the list sorted? Each answer changes the code a little, and asking shows the interviewer you read inputs carefully.

Why interviewers still ask it

Two Sum is short enough to finish in ten minutes, which is exactly why it gets used. It shows up as a warm-up in phone screens, as the first half of a longer round, or as a quick check that a candidate can write code that runs at all. The real signal is whether you see the trade of memory for time without being led there. Strong candidates name the nested loop, say it is quadratic, and then reach for a dictionary on their own.

Follow-ups that often come next

  • What if the list is sorted? Two pointers from both ends solve it in O(n) time and O(1) extra space. Move the left pointer right when the sum is too small and the right pointer left when it is too big.
  • Return every pair, not just one. Decide whether pairs are by value or by index, and how to avoid reporting the same pair twice.
  • Three numbers that sum to the target. Sort, fix one number, then run the two-pointer scan on the rest. That is O(n²), the usual expected bound.
  • The numbers arrive as a stream. Keep a running dictionary of counts and answer each query by looking up the complement, which is the same idea spread over time.
  • No hash map allowed. Sort (value, original index) pairs and run two pointers. That is O(n log n) time and still O(n) space for the pairs, so it avoids hashing rather than saving memory. If only the values are needed, sorting in place brings extra space down to what the sort itself uses.

Brute force: check every pair

The obvious answer tries every pair of positions. With n numbers there are about n²/2 pairs, so the time is O(n²) and the extra space is O(1). It is fine for a list of fifty items and far too slow for a million. Say it out loud anyway; it frames what the better solution saves.

def pair_indexes_slow(values, goal):
    n = len(values)
    for i in range(n):
        for j in range(i + 1, n):
            if values[i] + values[j] == goal:
                return [i, j]
    return []
Brute force, O(n²) time and O(1) extra space.

Optimal approach: one pass with a hash map

Look at what the inner loop is doing. For a fixed number x, it searches the rest of the list for the value goal minus x, which we call the complement. A dictionary from value to index answers that question in constant time on average. Walk the list once. For each number, compute its complement and check the dictionary. If the complement is there, you are done. If not, store the current number with its index and keep going.

Checking before storing is the detail that matters. It means a number can never be paired with itself, and it handles duplicates for free: with [6, 6] and a target of 12, the second 6 finds the first one already stored.

def pair_indexes(values, goal):
    seen = {}  # value -> index where it appeared
    for i, x in enumerate(values):
        need = goal - x
        if need in seen:
            return [seen[need], i]
        seen[x] = i
    return []
Python: one pass, O(n) time and O(n) space.
function pairIndexes(values, goal) {
  const seen = new Map(); // value -> index
  for (let i = 0; i < values.length; i++) {
    const need = goal - values[i];
    if (seen.has(need)) return [seen.get(need), i];
    seen.set(values[i], i);
  }
  return [];
}
JavaScript: the same idea with a Map, which keeps number keys as numbers.

For the sorted follow-up, the two-pointer version needs no dictionary at all.

def pair_in_sorted(values, goal):
    lo, hi = 0, len(values) - 1
    while lo < hi:
        total = values[lo] + values[hi]
        if total == goal:
            return [lo, hi]
        if total < goal:
            lo += 1
        else:
            hi -= 1
    return []
Sorted input: two pointers, O(n) time and O(1) extra space.

Complexity

Time and extra space for each version
ApproachTimeExtra spaceWhen to use it
Every pairO(n²)O(1)Tiny inputs, or as the opening statement
Hash map, one passO(n) averageO(n)The default answer for unsorted input
Sort, then two pointersO(n log n)O(n) to keep original indexesWhen a hash map is ruled out
Two pointers on sorted inputO(n)O(1)When the list arrives already sorted
Time and extra space for each version. Scroll sideways on a small screen.

The hash map's O(n) is an average. A dictionary with many colliding keys can degrade, which is rarely an issue in an interview but worth one sentence if the interviewer pushes on worst cases.

Edge cases to test

  • An empty list or a single element: no pair exists, so return whatever you agreed on, such as an empty list.
  • Duplicates that form the answer, like [6, 6] with a target of 12.
  • A value that is exactly half the target but appears only once, like [6, 1] with a target of 12. It must not pair with itself.
  • Negative numbers and zero.
  • Large values in a language with fixed-size integers, where the sum could overflow. Python integers do not overflow; Java and C++ ints can.
  • No valid pair, if the interviewer relaxes the guarantee that one exists.

Mistakes that cost points

  • Storing every number first and then searching. That can pair an element with itself unless you add an index check.
  • Returning the values instead of the indexes, or sorting the list and returning positions in the sorted copy.
  • Writing two passes and calling it one pass. Two passes are still O(n), but say what you wrote.
  • Claiming O(1) space for the hash map version.
  • Jumping to the dictionary without mentioning the brute force. Interviewers often want to hear the slower idea first.

How to explain it out loud

Fictional example

A walkthrough that takes about a minute
Candidate
The simplest approach checks every pair, which is quadratic. The inner loop is really asking one question: have I seen the number that completes this one?
Candidate
A dictionary from value to index answers that in constant time. I walk the list once, compute the complement, look it up, and only then store the current value. Storing after the check stops an element from pairing with itself.
Candidate
That is linear time and linear extra space. Let me trace [4, 9, 1, 7] with target 8: after 4, 9 and 1 the dictionary holds those three, and at 7 the complement 1 is found at index 2, so I return [2, 3].

The same dictionary habit drives Top K Frequent Elements, where a map counts values before you choose winners, and Longest Substring Without Repeating Characters, where a map records the last index of each character so a window can jump forward. For the sorted variant's pointer logic, Merge Intervals is a good next step. The full list is on the coding problems hub.

Practice it with Natively

During practice, Natively can take a screenshot of a problem like this one, read it, and suggest a pattern and an approach, so you can compare its idea with yours after you have tried on your own. It also transcribes a mock interview on your computer, which makes it easy to check whether you mentioned the brute force and the complexity. Read more about an AI interview assistant for Mac and Windows.

Questions people ask

What is the optimal solution to Two Sum?

One pass with a hash map. For each number, look up the value that would complete the target; if it is stored, return both indexes, otherwise store the current number with its index. It runs in O(n) time with O(n) extra space.

Why check the dictionary before adding the current number?

So an element can never pair with itself. Checking first also handles duplicates, because the second copy of a value finds the first one already stored.

How do you solve Two Sum when the array is sorted?

Use two pointers, one at each end. If the sum is too small move the left pointer right, if it is too big move the right pointer left. That is O(n) time and O(1) extra space.

Is Two Sum asked in real interviews?

It and its variants still appear, often as a warm-up or the first part of a longer problem. Interviewers mainly want to see you name the quadratic approach and move to the hash map yourself.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP