How to Explain Two Sum in a Coding Interview (Step-by-Step)

How to Explain Two Sum in a Coding Interview (Step-by-Step)

Two Sum is the most common warm-up question in coding interviews — and the one most candidates over-explain. The brute force is obvious. The key is quickly pivoting to the one-pass HashMap, explaining why it works, and handling the duplicate element edge case before the interviewer asks.

In this post, you’ll learn exactly how to walk an interviewer through Two Sum: the complement insight, the one-pass HashMap approach, a full step-by-step trace, and every edge case worth calling out.


Problem Statement

LeetCode 1 Easy

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

You may assume each input has exactly one solution, and you may not use the same element twice.

Examples

Example 1
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1] → nums[0] + nums[1] = 2 + 7 = 9
Example 2
Input: nums = [3, 2, 4], target = 6
Output: [1, 2] → nums[1] + nums[2] = 2 + 4 = 6
Example 3
Input: nums = [3, 3], target = 6
Output: [0, 1] → nums[0] + nums[1] = 3 + 3 = 6

Constraints

  • 2 <= nums.length <= 10⁴
  • -10⁹ <= nums[i] <= 10⁹
  • -10⁹ <= target <= 10⁹
  • Only one valid answer exists

What Is the Problem?

“Given an array and a target, find the indices of two numbers that sum to the target. The array is unsorted, I can’t use the same element twice, and exactly one solution is guaranteed.”

Saying “unsorted” signals to the interviewer that you know two pointers won’t work here — which naturally leads to the HashMap approach.


Step 1: Walk Through All Three Approaches

❌ Brute Force

Two nested loops — try every pair

Time: O(n²)

Space: O(1)

⚠️ Sort + Two Pointers

Sort first, then squeeze inward

Time: O(n log n)

Space: O(n)

Loses original indices after sort

✅ One-Pass HashMap

Store complement while scanning

Time: O(n)

Space: O(n)

“The sort + two pointer approach loses the original indices unless we store them separately — adds complexity for no benefit. The HashMap approach gives us O(n) time in a single pass and naturally preserves indices.”

The Key Insight — Complements

💡 Core Insight

For any number nums[i], the number we need to pair with it is target − nums[i] — its complement. Instead of searching the array for the complement every time (O(n) per lookup), we store numbers we’ve already seen in a HashMap. Then for each new number, we check the HashMap in O(1).

This converts a two-pass problem into a one-pass problem — we store and check simultaneously.


Step 2: Explain the Algorithm in Plain English

“I scan through the array with a single loop. For each element, I compute its complement: target − nums[i]. I check if the complement is already in my HashMap. If it is — I’ve found the pair, return both indices. If not — I store the current number and its index in the HashMap and move on.”

Step 3: Talk Through the Code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        seen = {}  # Maps number → its index in nums

        for i, num in enumerate(nums):
            complement = target - num   # What we need to complete the pair

            if complement in seen:
                return [seen[complement], i]  # Found it — return both indices

            seen[num] = i   # Not found yet — store this number for future lookups

        # Problem guarantees one solution so we never reach here

Point out that we check before inserting — this ensures we never accidentally use the same element twice as its own complement (e.g. num = 5, target = 10).


Visual Walkthrough

Tracing through nums = [2, 7, 11, 15], target = 9:

One-pass HashMap trace — complement check before insert
0
num = 2  |  complement = 9 − 2 = 7
Is 7 in seen? No → store {2: 0}
seen = {2: 0}
miss
1
num = 7  |  complement = 9 − 7 = 2
Is 2 in seen? ✅ YES → return [seen[2], 1] = [0, 1]
seen = {2: 0}
→ [0, 1] ★

Full trace for nums = [3, 2, 4], target = 6:

inumcomplementin seen?seen after stepresult
033no{3: 0}
124no{3:0, 2:1}
242YES ★[1, 2]

Step 4: Highlight Edge Cases

1 Duplicate values — same number needed twice
“e.g. [3, 3] with target = 6. When we process index 0 (num=3), complement=3 is not in seen yet — so we store it. When we process index 1 (num=3), complement=3 IS now in seen with index 0. We return [0, 1]. The check-before-insert order handles this correctly without extra logic.”
2 Negative numbers
“The constraints allow negative values. target − num works perfectly — e.g. nums = [-3, 7], target = 4: complement of -3 is 7, complement of 7 is -3. The HashMap handles negative keys without any special casing.”
3 Answer at the very beginning
“The answer could be at indices [0, 1]. We process index 0 first, store it, then on index 1 find the complement and return immediately. Works correctly.”
4 Why not use the same element twice?
“e.g. nums = [5, 3], target = 10. When we reach num = 5, complement = 5. We check before inserting — so 5 is not in seen yet. We store it and move on. We never return [0, 0]. The insert-after-check order is the safeguard.”

Step 5: State Time and Space Complexity

ApproachTimeSpace
Brute Force O(n²) O(1)
Sort + Two Pointers O(n log n) O(n)
One-Pass HashMap ✓ O(n) O(n)
“We visit each element exactly once. Each HashMap lookup and insert is O(1) average. Space is O(n) because in the worst case we store every element before finding the answer on the last step.”

Interview Checklist for Two Sum

  • Restate — “find indices of two numbers that sum to target, array is unsorted”
  • Mention brute force O(n²) and dismiss it
  • Mention sort + two pointers, explain why it loses original indices
  • State the key insight — store complement in HashMap while scanning
  • Explain check-before-insert — prevents using same element twice
  • Walk through the duplicate values case — [3, 3] target 6
  • Handle negative numbers — complement math still works
  • State O(n) time and O(n) space
  • Ask before coding, don’t just dive in

If you can solve Two Sum cleanly, try these next:

💡 Practicing your explanations out loud is just as important as writing correct code. The best candidates aren’t the ones who solve it fastest — they’re the ones who make the interviewer feel like they’re thinking alongside them.

Scroll to Top