Target-Sum Index Pair

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement two_sum(nums: List[int], target: int) -> List[int], which receives an unsorted list of integers nums and a desired integer sum target.

Locate two different 0-based positions i and j (i != j) in nums such that nums[i] + nums[j] == target, and return [i, j].

Your implementation should satisfy these rules:

  • No self-pairing: You may never reuse the same array position twice, even when 2 * nums[i] == target. However, two identical numbers located at distinct positions (i != j) are valid partners.
  • Arbitrary integer signs: Entries in nums as well as target can be negative, zero, or positive, and nums is not ordered.
  • Multiple or missing solutions: When more than one valid pair of positions exists, returning any single valid pair is accepted. When no two distinct positions add up to target (including lists with fewer than two items), return [].
  • Efficiency: Aim for O(n) average runtime by trading auxiliary memory for fast lookups.

Examples

Example 1

nums = [9, 4, 12, 5]
target = 14
# Output: [0, 3]

Explanation: nums[0] + nums[3] = 9 + 5 = 14, and no other pair of distinct positions produces 14.

Example 2

nums = [5, -2, 7, 12]
target = 10
# Output: [1, 3]

Explanation: Position 0 holds 5, which cannot be added to itself because i != j is required. Pairing position 1 (-2) with position 3 (12) gives -2 + 12 = 10.

Example 3

nums = [6, 1, 6]
target = 12
# Output: [0, 2]

Explanation: Duplicate values at separate positions are allowed: nums[0] and nums[2] are both 6, so [0, 2] sums to 12.

Constraints

  • 0 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9

Step-by-step walkthrough

  1. Clarify the rules and boundary behaviors

    We receive an unsorted integer list nums and an integer target, and we must return [i, j] (i != j) where nums[i] + nums[j] == target.

    Pin down the tricky cases before writing code:

    • Distinct positions (i != j), not distinct values: [6, 1, 6] with target = 12 returns [0, 2], whereas [5, 7] with target = 10 has no valid pair because index 0 cannot be used twice.
    • Negatives and zeros: Allowed anywhere in nums or target ([5, -2, 7, 12] with target = 10 returns [1, 3]), so we must never skip values larger than target.
    • Missing solution: When no two distinct indices add up to target (or len(nums) < 2), returning [] fits the List[int] return type cleanly.
  2. Brute force: why checking all pairs takes O(n²)

    The straightforward baseline compares every pair of positions i < j:

    def two_sum_brute(nums, target):
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return []
    

    This uses O(1) extra space, which is optimal for memory, but inspects up to n * (n - 1) / 2 pairs — roughly 5 billion checks at n = 100,000. Whenever the outer scan stands at nums[j], only one exact partner value can complete the sum: target - nums[j]. Re-scanning earlier indices on every step is what costs O(n) per element.

  3. Key idea: trade O(n) memory for O(1) complement lookups

    At current_index with value num, let complement = target - num be the exact partner we need. Rather than scanning backward, we keep a hash map (a Python dict, providing O(1) average-time key lookups) named seen_index that maps each already-visited number to an index where it appeared:

    target = 14,  nums = [9, 4, 12, 5]
    
    current_index = 0, num = 9:
      complement = 14 - 9 = 5   -> is 5 in seen_index {}? No.
      record seen_index[9] = 0  -> seen_index is {9: 0}
    
    current_index = 1, num = 4:
      complement = 14 - 4 = 10  -> is 10 in {9: 0}? No.
      record seen_index[4] = 1  -> seen_index is {9: 0, 4: 1}
    
    current_index = 2, num = 12:
      complement = 14 - 12 = 2  -> is 2 in {9: 0, 4: 1}? No.
      record seen_index[12] = 2 -> seen_index is {9: 0, 4: 1, 12: 2}
    
    current_index = 3, num = 5:
      complement = 14 - 5 = 9   -> is 9 in seen_index? YES, at index 0!
      return [0, 3] immediately
    

    A single left-to-right pass finds any valid pair i < j: when the loop visits the earlier position i, it stores nums[i] in seen_index, so when the loop reaches the later position j, complement = target - nums[j] = nums[i] is already waiting in the dictionary.

  4. Why lookup must happen before insert

    On each iteration we check complement in seen_index and write seen_index[num] = current_index. Doing the lookup first prevents an element from matching itself when target == 2 * num:

    Case A: nums = [5, 7], target = 10 (only ONE 5 -> must NOT match itself)
      index 0, num = 5, complement = 5:
        1. Lookup 5 in {} -> NOT found (5 has not been inserted yet)
        2. Insert seen_index[5] = 0
    
    Case B: nums = [6, 1, 6], target = 12 (TWO 6s -> MUST match [0, 2])
      index 0, num = 6: lookup 6 in {} -> miss; insert seen_index[6] = 0
      index 1, num = 1: lookup 11 in {6: 0} -> miss; insert seen_index[1] = 1
      index 2, num = 6: lookup 6 in {6: 0, 1: 1} -> HIT at index 0! Return [0, 2]
    

    Checking before inserting guarantees every index stored in seen_index is strictly smaller than current_index: - No position ever pairs with itself (seen_index[complement] < current_index). - Duplicate numbers work automatically ([6, 1, 6] matches index 0 when visiting index 2; if a duplicate has not completed target yet, overwriting seen_index[num] still leaves a valid earlier index for any later element). - The returned pair [seen_index[complement], current_index] comes out in ascending index order.

    from typing import Dict, List
    
    
    def two_sum(nums: List[int], target: int) -> List[int]:
        seen_index: Dict[int, int] = {}
        for current_index, num in enumerate(nums):
            complement = target - num
            if complement in seen_index:
                return [seen_index[complement], current_index]
            seen_index[num] = current_index
        return []
    
  5. Trace Example 2 and compare the three main designs

    Trace nums = [5, -2, 7, 12], target = 10 step by step:

    current_index=0, num=5:  complement = 10 - 5 = 5
      5 in {}? No -> seen_index becomes {5: 0}
    
    current_index=1, num=-2: complement = 10 - (-2) = 12
      12 in {5: 0}? No -> seen_index becomes {5: 0, -2: 1}
    
    current_index=2, num=7:  complement = 10 - 7 = 3
      3 in {5: 0, -2: 1}? No -> seen_index becomes {5: 0, -2: 1, 7: 2}
    
    current_index=3, num=12: complement = 10 - 12 = -2
      -2 in {5: 0, -2: 1, 7: 2}? Yes, at index 1! -> return [1, 3]
    

    Notice how 5 at index 0 avoided pairing with itself, and 12 > target still combined with -2 to hit 10.

    Approach Time Extra Space Trade-off
    Brute force (all pairs) O(n²) O(1) Zero extra memory, but far too slow for large n.
    Sort (value, orig_idx) + two pointers O(n log n) O(n) Still uses O(n) memory to remember original positions before sorting.
    One-pass hash map O(n) avg O(n) Fastest runtime; trades O(n) dictionary memory for O(1) average lookups.
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def two_sum(nums: List[int], target: int) -> List[int]:
        # seen_index: {number: index_of_an_earlier_occurrence}, e.g. {5: 0, -2: 1}
        seen_index: Dict[int, int] = {}
    
        # Phase 1: Scan left to right, pairing each number against earlier numbers.
        for current_index, num in enumerate(nums):
            complement = target - num
    
            # Phase 2: Check seen_index BEFORE inserting num so an element at
            # current_index never pairs with itself (e.g. nums=[5, 7], target=10).
            if complement in seen_index:
                return [seen_index[complement], current_index]
    
            # Phase 3: Record num's index for future elements to match against.
            # Overwriting an older duplicate index is safe because any single earlier
            # index with this value forms an equally valid distinct pair.
            seen_index[num] = current_index
    
        # No two distinct indices sum to target.
        return []
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture numbered tiles sliding past you one by one on a conveyor belt while you look for two tiles that add up to 10. Instead of grabbing each new tile and walking all the way back to inspect every earlier tile on the belt, you keep a labeled storage rack (a hash map, or Python dict) recording each value you have already seen and its position. When 12 arrives, the exact partner needed to reach 10 — its complement — is 10 - 12 = -2, so you check slot -2 on the rack: if an earlier index is sitting there, you return both indices right away; otherwise you place 12's index into slot 12 and move on.

The naive nested-loop solution compares every pair (i, j), performing up to n * (n - 1) / 2 additions — roughly 5 billion checks when n = 100,000 — because it repeatedly scans the same prefix of numbers. Spending O(n) memory on a dictionary turns each backward scan into an O(1) average-time lookup, finishing the entire search in a single O(n) pass.

Walk through nums = [5, -2, 7, 12] with target = 10: 1. current_index = 0, num = 5: complement = 10 - 5 = 5. seen_index is {}, so 5 is not present yet; store seen_index[5] = 0. 2. current_index = 1, num = -2: complement = 10 - (-2) = 12. 12 is not in {5: 0}; store seen_index[-2] = 1. 3. current_index = 2, num = 7: complement = 10 - 7 = 3. 3 is not in {5: 0, -2: 1}; store seen_index[7] = 2. 4. current_index = 3, num = 12: complement = 10 - 12 = -2. -2 is in {5: 0, -2: 1, 7: 2} at index 1, so return [1, 3].

Complexity

  • Time: O(n) on average, where n is len(nums). We step through nums at most once, doing one O(1) average-time dictionary lookup and at most one O(1) average-time insertion per element. (In a pathological worst case where crafted integer keys cause repeated hash collisions — many distinct keys landing in the same internal bucket — lookups degrade to O(n), giving O(n²) worst-case time; on normal inputs runtime is linear.)
  • Space: O(n) extra memory in the worst case (specifically O(u) for u distinct values visited prior to a match), since seen_index holds at most one index per unique number when no pair matches until the end.

Edge cases

  • Empty list or single item ([], [5]): Fewer than two elements cannot form a pair, so the loop finishes and returns [].
  • No matching pair ([1, 2, 3, 9], target = 100): Every element enters seen_index without a hit and [] is returned cleanly.
  • Half-target single value vs duplicate (target = 12 on [6, 1] vs [6, 1, 6]): Checking before inserting returns [] on [6, 1] (never pairing index 0 with itself) and [0, 2] on [6, 1, 6].
  • Duplicates separated by unrelated items ([1, 5, 2, 5], target = 10): Index 1 records seen_index[5] = 1, which index 3 later matches to return [1, 3].
  • Negative values and zeros ([-3, 4, 3, 90] with target = 0, or [0, 5, 0] with target = 0): target - num works identically regardless of sign, returning [0, 2].
  • Fixed-width integer overflow in other languages: Python integers have unbounded precision, whereas in C++ or Java target - num can overflow 32-bit int (such as INT_MIN - 1) unless computed in long long / long.

Common mistakes

  • Writing seen_index[num] = current_index before testing complement in seen_index: Causes [5, -2, 7, 12] with target = 10 to match index 0 (5) with itself and return [0, 0].
  • Building {num: idx} in a separate first pass without checking seen_index[complement] != current_index: Also pairs a half-target element with itself unless guarded by an index inequality check.
  • Sorting nums in place for two pointers and returning the sorted indices: Loses the original positions requested by the caller; you must pair each value with its original index before sorting.
  • Ignoring elements where num > target: Fails whenever negative numbers appear ([5, -2, 7, 12] needs 12 > 10 to pair with -2).
  • Returning [complement, num] (the numbers) rather than [i, j] (their 0-based positions).

Alternative approaches

  • Sort (value, index) pairs + two pointers: Attach each element's original index, sort by value in O(n log n) time, and walk left and right pointers inward. Because keeping original positions still costs O(n) extra memory, it is slower than O(n) hashing on unsorted lists, though if a variant only asked for True/False and allowed in-place sorting, two pointers would avoid dictionary allocation.

Follow-up questions

  • How can you achieve O(1) extra memory if the input list is already sorted in non-decreasing order? Apply the two-pointer technique (starting left = 0 at the minimum element and right = len(nums) - 1 at the maximum element, stepping one boundary inward per iteration): when nums[left] + nums[right] < target, advance left to raise the sum; when the sum exceeds target, move right leftward to lower it; when equal, return [left, right]. Each comparison permanently eliminates one end without allocating a dictionary, giving O(n) time and O(1) auxiliary space.
  • What changes if you need to return every valid pair rather than stopping at the first match? First clarify whether the caller wants all index pairs (i, j) or all unique value pairs (a, b). For index pairs, map each value to a list of prior positions (seen_indices[num].append(j)) and emit (i, j) for every i in seen_indices[complement], running in O(n + k) time for k output pairs (up to O(n²) if every entry is 0 and target = 0). For unique value pairs, maintain a visited set and insert (min(num, complement), max(num, complement)) into a pairs set in O(n) average time.
  • How would you extend this approach to find three distinct indices whose values add up to target? Pair every number with its original position, sort by value in O(n log n) time, loop i from 0 to n - 3 to anchor the first element, and run an inward two-pointer scan across i + 1 .. n - 1 targeting target - nums[i]. That brings runtime down from O(n³) brute force to O(n²) using O(n) space for the index pairs (or O(1) extra space when returning deduplicated value triples from an in-place sort while skipping adjacent duplicates).

Follow-up questions

Similar questions

More Aeonea interview questions

All 3 Aeonea questions →