EasyπŸ‘€ 0-2 yearsπŸ‘€ 3-5 years 4 min read Updated Aug 15, 2026

Two Sum Interview Question

Reviewed by Gurusankar M. Β· Updated Aug 15, 2026

Asked inAmazonAccentureDeloitte
#two sum#hashmap#leetcode#array#python#time complexity#space complexity
Report issue

⚑ Short Answer

Scan the array once, keeping a HashMap of value β†’ index for numbers already seen. For each number, check whether target - number is already in the map before inserting the current number β€” if it is, you've found your pair in O(n) time and O(n) space, versus the O(nΒ²) brute-force nested-loop check.

β˜•Coffee Chat Question

Concept Made Simple

β€œSolve Two Sum β€” return indices of two numbers adding to a target.”

🧠Mind Map Answer

Remember It Faster

Brute force is O(nΒ²) with nested loops. The trick: as you scan, remember what you have seen in a HashMap so you can look up the complement in O(1).

Need→target - current
Store→value → index seen so far
Time→O(n), one pass

Why indices, not values? The same value can appear twice in the array, so returning the values themselves would be ambiguous β€” the index is what unambiguously identifies which element was used. It's also why the lookup happens before inserting the current number: checking target - n in seen first stops an element from pairing with itself.

Duplicates and "no pair found" are the two edge cases interviewers actually probe. If the same value appears twice and their indices sum to the target, the HashMap approach handles it correctly for free β€” the first occurrence is stored by the time the second is scanned, so the lookup succeeds without any special-casing. If no pair sums to the target, the loop finishes with nothing to return; most implementations either return an empty list / None or raise an explicit error β€” LeetCode's version guarantees exactly one solution exists, but a production version of this pattern (e.g. matching two transactions that net to zero) should decide and document which behavior it wants, since "guaranteed to exist" is rarely true outside a coding-interview problem statement.

Is the HashMap approach really O(n)? Strictly, that's the average-case bound β€” it assumes hash collisions are rare, which is the normal case with Python's/Java's default string and integer hashing. A senior-level follow-up worth having an answer for: with a pathological hash function (or a hand-crafted adversarial input designed to collide), every lookup could degrade toward O(n), making the overall algorithm O(nΒ²) in the worst case β€” theoretically identical to brute force, just with extra hashing overhead on top. This is precisely why Java's HashMap treeifies long collision chains (O(n) β†’ O(log n) worst case per bucket, covered on the HashMap resize page) rather than leaving them as plain linked lists β€” it caps exactly this worst case rather than eliminating the possibility of collisions entirely.

"What if we needed three numbers instead of two?" is the near-universal next question, and the HashMap trick doesn't extend directly β€” a triple nested loop with a HashMap lookup on the innermost is still O(nΒ²) (one fixed index, one HashMap-assisted Two Sum on the rest), not O(n). The standard Three Sum solution instead sorts the array first (O(n log n)), then fixes one element and runs the sorted two-pointer technique on the remainder for each fixed element β€” O(nΒ²) overall, but with O(1) extra space instead of a HashMap, and sorting also makes duplicate-triplet skipping trivial (skip past repeated values at each pointer), which is normally the fiddliest part of a naive HashMap-based attempt at three (or more) numbers. Interviewers rarely expect the full Three Sum solution as a follow-up to Two Sum β€” naming this trade-off (sort + two-pointer over nested HashMap lookups, and why) is usually enough to demonstrate the pattern generalizes.

python
# Two-pointer variant β€” only valid once the array is SORTED
def two_sum_sorted(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return [lo, hi]
        elif s < target:
            lo += 1          # sum too small, need a bigger left value
        else:
            hi -= 1           # sum too big, need a smaller right value
    return None               # no pair sums to target

⌨️Hands-on Keyboard

Learn by Doing

python
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        if target - n in seen:
            return [seen[target - n], i]
        seen[n] = i

print(two_sum([2, 7, 11, 15], 9))
Output
[0, 1]
⏱️ Time: O(n) β€” one passπŸ’Ύ Space: O(n) β€” the hash map storing up to n values

πŸ”₯What If?

Think Beyond the Expected

What if the array is already sorted?

Use the two-pointer technique β€” one at each end, move them inward based on the sum. That is O(n) time and O(1) space, beating the HashMap on memory.

πŸ˜‚Real World

Two Sum is the 'hello world' of the HashMap-for-lookup pattern. The same trick β€” remember what you've seen so the complement is O(1) β€” shows up in deduplication, caching, and detecting pairs/anagrams across real codebases.

🎯Interviewer's Expectation

Keywords they're listening for:

βœ“ brute force O(nΒ²) firstβœ“ HashMap β†’ O(n)βœ“ space-time trade-offβœ“ two-pointer if sortedβœ“ why indices, not values

⚠️Common Mistakes

  • βœ—Checking `n in seen` after inserting the current number β€” lets an element pair with itself
  • βœ—Jumping straight to the HashMap solution without first stating the brute-force O(nΒ²) baseline
  • βœ—Not stating space complexity alongside time complexity
  • βœ—Not clarifying whether duplicates are allowed or exactly one solution is guaranteed

βœ…Best Practices

  • βœ“Start with brute force, then optimize β€” show the trade-off, don't skip to the answer
  • βœ“State time AND space complexity explicitly
  • βœ“Ask clarifying questions: duplicates allowed? Exactly one solution guaranteed?

πŸ”Follow-up Questions

  • 1Why does the problem ask for indices instead of the actual values?
  • 2What's the time and space complexity of the HashMap approach?
  • 3What if the array has duplicate values?
  • 4What should the function return if no valid pair exists?
  • 5How would you solve Two Sum if the array were already sorted?

🧩Related Technologies

HashMaptwo-pointer techniqueLeetCode

πŸ“šReferences

Continue Learning with AI

Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly β€” AI is your learning companion, not a shortcut.

Plain-language foundations

I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner.

Topic: HashMaps (Coding Challenges)
Interview question: "Solve Two Sum β€” return indices of two numbers adding to a target."

Please:
1. Explain the core idea in simple, plain language, using an everyday analogy.
2. Define any technical terms you use.
3. Walk through one small, concrete example.
4. Finish with a single sentence I can easily remember.

Keep the tone friendly and assume I'm new to this topic.

Was this answer helpful?

Support our platform by exploring our recommended products.

As an Amazon affiliate, purchases through these links may earn us a small commission β€” at no extra cost to you. It helps keep Full Stack Interview Guru free.

Related Questions