Two Sum With Lexicographic Index Tie-Breaking

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given an unsorted list of integers nums and an integer target, find two distinct positions i and j satisfying 0 <= i < j < len(nums) whose values add up to target (nums[i] + nums[j] == target), and return [i, j].

def two_sum_lexicographically_smallest(nums: List[int], target: int) -> List[int]:
  • Indices are 0-based, and an element may never be paired with itself (i < j is strictly required).
  • Whenever two or more valid index pairs produce target, choose the lexicographically earliest pair: minimize the first index i above all else, and if multiple candidates share that smallest i, minimize the second index j.
  • Every test input is guaranteed to have at least one valid pair.

Examples

Example 1

Input: nums = [2, 5, 5, 8], target = 10
Output: [0, 3]

Both [0, 3] (2 + 8 = 10) and [1, 2] (5 + 5 = 10) sum to 10. Comparing first indices gives 0 < 1, so [0, 3] beats [1, 2] even though index 2 appears before index 3.

Example 2

Input: nums = [4, -1, 9], target = 8
Output: [1, 2]

Although 4 + 4 = 8, index 0 cannot be used twice. The unique valid pair is nums[1] + nums[2] = -1 + 9 = 8 at [1, 2].

Example 3

Input: nums = [6, 1, 4, 4], target = 10
Output: [0, 2]

Both [0, 2] and [0, 3] start at i = 0 and sum to 10 (6 + 4 = 10). Breaking the tie on the second index chooses the smaller j = 2, returning [0, 2].

Example 4

Input: nums = [-2, -2], target = -4
Output: [0, 1]

Positions 0 and 1 are distinct (0 < 1) and -2 + (-2) = -4, producing [0, 1].

Constraints

  • 2 <= len(nums) <= 10^5
  • -10^9 <= nums[k] <= 10^9 for every 0 <= k < len(nums)
  • -2 * 10^9 <= target <= 2 * 10^9
  • At least one pair (i, j) with 0 <= i < j < len(nums) satisfies nums[i] + nums[j] == target.

Step-by-step walkthrough

  1. Understand lexicographic tie-breaking on index pairs

    Given an unsorted integer list nums and an integer target, we must return 0-based indices [i, j] with i < j and nums[i] + nums[j] == target.

    When multiple valid pairs exist, lexicographically smallest means comparing [i, j] the same way words are ordered in a dictionary — compare the first index i first, and only use j to break ties when i is identical:

    Compare [0, 3] vs [1, 2]:  first index 0 < 1         --> [0, 3] wins (even though 3 > 2!)
    Compare [0, 2] vs [0, 3]:  first index tied, 2 < 3   --> [0, 2] wins
    Self-pair [0, 0]:          violates i < j            --> forbidden!
    
  2. Brute force tries pairs in exact lexicographic order

    A nested loop with i from 0 to n - 1 and j from i + 1 to n - 1 visits pairs in exact lexicographic order [0, 1], [0, 2], ..., [1, 2], ..., so the very first match is guaranteed to be optimal:

    def brute_two_sum(nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return []
    

    That makes an ideal test oracle, but in the worst case (when the only valid pair sits at [n - 2, n - 1]) it checks n * (n - 1) / 2 pairs — roughly 5 * 10^9 operations for n = 100,000, which is far too slow.

  3. Why the standard left-to-right Two Sum breaks tie-breaking

    In the textbook O(n) Two Sum, you scan j from left to right, store seen numbers in a dictionary, and return immediately on the first match. Watch what happens on Example 1 (nums = [2, 5, 5, 8], target = 10):

    Index:     0   1   2   3
    nums:    [ 2,  5,  5,  8 ]    target = 10
               |   |---|   |
               |   [1,2]   |      <-- Left-to-right scan hits j=2 first and returns [1, 2]!
               +-----------+
                   [0,3]          <-- True answer is [0, 3] because i=0 < i=1!
    

    Stopping on the first j optimizes for the smallest j, whereas our problem demands the smallest i first!

  4. Key insight: sweep from right to left

    Suppose we fix i and look only to the right of i (indices i + 1 .. n - 1). Which partner j > i does i want? The smallest index after i where target - nums[i] appears!

    If we sweep i backward from len(nums) - 1 down to 0 and maintain a dictionary earliest_after mapping each value to its smallest index seen to the right of i, three requirements fall into place automatically:

                     i  <---  sweep i right-to-left
    nums:  [ ... , nums[i] |  nums[i+1],  ... ,  nums[n-1]  ]
                           |--------- earliest_after -------|
                            maps each value -> smallest j > i
    
    1. Guarantee i < j: Look up needed_val = target - nums[i] before inserting nums[i], so earliest_after contains only indices strictly greater than i.
    2. Smallest j for a given i: After the lookup, unconditionally assign earliest_after[current_val] = i. Because i is smaller than any index we visited earlier, overwriting always keeps the leftmost copy in the suffix!
    3. Smallest i overall: Keep scanning all the way to i = 0 without returning early. Every time needed_val in earliest_after, overwrite best_pair = [i, earliest_after[needed_val]] — because i strictly decreases on each iteration, every newly found pair has a strictly smaller i than any previous match!
    def two_sum_lexicographically_smallest(nums: List[int], target: int) -> List[int]:
        # earliest_after: dict {value: smallest_index_after_i}, e.g. {5: 1, 1: 2}
        earliest_after: Dict[int, int] = {}
        # best_pair: [i, j] holding the smallest i (and smallest j for that i) found so far
        best_pair: List[int] = []
    
        # Phase 1: Sweep i from right to left so earliest_after only contains indices j > i.
        for i in range(len(nums) - 1, -1, -1):
            current_val = nums[i]
            needed_val = target - current_val
    
            # Phase 2: Look up partner BEFORE recording nums[i] so index i never pairs with itself.
            if needed_val in earliest_after:
                # Because i strictly decreases each step, this new i beats every previously found pair,
                # and earliest_after[needed_val] already holds the smallest j > i for this i.
                best_pair = [i, earliest_after[needed_val]]
    
            # Phase 3: Always overwrite with the smaller index i so future lookups get the nearest j.
            earliest_after[current_val] = i
    
        return best_pair
    
  5. Trace Example 3 and Example 1

    First trace Example 3 (nums = [6, 1, 4, 4], target = 10):

    i   current   needed   earliest_after (before)   match?        best_pair   earliest_after (after)
    -   -------   ------   -----------------------   -----------   ---------   ----------------------
    3   4         6        {}                        no            []          {4: 3}
    2   4         6        {4: 3}                    no            []          {4: 2}         (4 updated 3->2!)
    1   1         9        {4: 2}                    no            []          {4: 2, 1: 1}
    0   6         4        {4: 2, 1: 1}              yes -> j=2    [0, 2]      {4: 2, 1: 1, 6: 0}
    

    At i = 2, overwriting earliest_after[4] = 2 replaced index 3 with the nearer index 2, so i = 0 paired with j = 2 ([0, 2]) instead of [0, 3].

    Now trace Example 1 (nums = [2, 5, 5, 8], target = 10):

    i   current   needed   earliest_after (before)   match?        best_pair   earliest_after (after)
    -   -------   ------   -----------------------   -----------   ---------   ----------------------
    3   8         2        {}                        no            []          {8: 3}
    2   5         5        {8: 3}                    no            []          {8: 3, 5: 2}
    1   5         5        {8: 3, 5: 2}              yes -> j=2    [1, 2]      {8: 3, 5: 1}
    0   2         8        {8: 3, 5: 1}              yes -> j=3    [0, 3]      {8: 3, 5: 1, 2: 0}
    

    At i = 1 we temporarily record [1, 2], and at i = 0 we find [0, 3], overwriting best_pair and returning [0, 3].

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def two_sum_lexicographically_smallest(nums: List[int], target: int) -> List[int]:
        # earliest_after: dict {value: smallest_index_after_i}, e.g. {5: 1, 1: 2}
        earliest_after: Dict[int, int] = {}
        # best_pair: [i, j] holding the smallest i (and smallest j for that i) found so far
        best_pair: List[int] = []
    
        # Phase 1: Sweep i from right to left so earliest_after only contains indices j > i.
        for i in range(len(nums) - 1, -1, -1):
            current_val = nums[i]
            needed_val = target - current_val
    
            # Phase 2: Look up partner BEFORE recording nums[i] so index i never pairs with itself.
            if needed_val in earliest_after:
                # Because i strictly decreases each step, this new i beats every previously found pair,
                # and earliest_after[needed_val] already holds the smallest j > i for this i.
                best_pair = [i, earliest_after[needed_val]]
    
            # Phase 3: Always overwrite with the smaller index i so future lookups get the nearest j.
            earliest_after[current_val] = i
    
        return best_pair
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

We want the pair of indices [i, j] (i < j, nums[i] + nums[j] == target) that comes first in lexicographical order (dictionary order on pairs: compare the first index i first, and only compare the second index j when i is tied). Think of standing at the right end of the array and walking backward toward index 0 while keeping a hash map (a key-value lookup table — Python's dict — that finds and updates keys in O(1) average time) of the most recently passed index for each number. Because you walk from right to left, "most recently passed" means the smallest index strictly to the right of i (j > i): every index i immediately finds its closest valid right-hand partner j, and because i keeps shrinking all the way to 0, the very last match you find automatically has the smallest i!

Why do the two obvious approaches fail? Checking every (i, j) pair with nested loops visits pairs in exact lexicographical order, but takes O(n^2) time — roughly 5 billion checks on 100,000 numbers. Meanwhile, the textbook left-to-right one-pass Two Sum stops at the first j that completes any pair, optimizing for the smallest j instead of the smallest i (on Example 1, nums = [2, 5, 5, 8], target = 10, it stops at j = 2 with [1, 2] and completely misses [0, 3]).

Let's walk through Example 1 (nums = [2, 5, 5, 8], target = 10) from right to left:

i = 3 (val 8, need 2): earliest_after = {}           -> no match;      store 8 -> {8: 3}
i = 2 (val 5, need 5): earliest_after = {8: 3}       -> no match;      store 5 -> {8: 3, 5: 2}
i = 1 (val 5, need 5): earliest_after = {8: 3, 5: 2} -> match! [1, 2]; store 5 -> {8: 3, 5: 1}
i = 0 (val 2, need 8): earliest_after = {8: 3, 5: 1} -> match! [0, 3] overwrites [1, 2]

Final answer: [0, 3]

Complexity

Let n = len(nums).

  • Time: O(n) average. The loop visits each of the n indices once from n - 1 down to 0, performing one subtraction, one O(1) average-time dictionary lookup (needed_val in earliest_after), and one O(1) average-time dictionary write (earliest_after[current_val] = i).
  • Space: O(n). In the worst case where all n numbers in nums are distinct, earliest_after stores n key-value pairs.

Edge cases

  • Duplicate values that pair together ([-2, -2], target = -4): At i = 1, earliest_after becomes {-2: 1}; at i = 0, we look up -2 before overwriting earliest_after[-2] = 0, cleanly producing [0, 1].
  • Single copy of target / 2 ([4, -1, 9], target = 8): Because lookup happens before insertion, nums[0] = 4 does not see itself in earliest_after, avoiding the illegal self-pair [0, 0] and returning [1, 2].
  • Multiple valid partners j for the best i ([6, 1, 4, 4], target = 10): As the scan passes i = 3 and then i = 2, earliest_after[4] updates from 3 to 2, so i = 0 picks [0, 2] rather than [0, 3].
  • Best pair finishes later than a competing pair ([2, 5, 5, 8], target = 10): Because we never return early during the backward scan, [0, 3] found at i = 0 overwrites [1, 2] found at i = 1.
  • Negative integers, zeros, and large magnitudes (+-10^9): Exact integer subtraction and hashing work identically regardless of sign, and Python integers have arbitrary precision so target - current_val never overflows.

Common mistakes

  • Stopping early on the first match during the right-to-left scan: The first match found while walking backward has the largest i, not the smallest i! You must finish scanning down to i = 0.
  • Inserting earliest_after[current_val] = i before checking if needed_val in earliest_after:: Whenever 2 * nums[i] == target, i immediately pairs with itself and returns [i, i], violating i < j.
  • Refusing to overwrite existing keys (if current_val not in earliest_after): During a right-to-left scan, keeping the first index seen keeps the rightmost (largest) j instead of the nearest (smallest) j, failing [6, 1, 4, 4] with [0, 3] instead of [0, 2].
  • Using the standard left-to-right Two Sum with early return: Returns the pair with the smallest j rather than the smallest i.

Alternative approaches

  • Left-to-right streaming scan keeping earliest occurrences (O(n) time, O(n) space): Scan j from 0 to n - 1 storing only the first (smallest) index where each value appeared (if val not in first_seen: first_seen[val] = j). Whenever target - nums[j] is in first_seen, form candidate = [first_seen[target - nums[j]], j] and keep the minimum candidate (still without returning early!). Because the globally optimal [i*, j*] must use the first occurrence of nums[i*] (otherwise an earlier copy would give an even smaller i), both scans return the exact same [i*, j*].
  • Value-to-index lists with binary search (O(n log n) time, O(n) space): Group all indices for each value into sorted lists, then test i = 0, 1, ... from left to right and binary-search (bisect_right) for the first partner index > i, returning on the very first i that succeeds.

Follow-up questions

  • How would you find all index triples (i, j, k) with i < j < k whose elements sum to zero when all values in the array are distinct? Tag every element with its original position [(val, idx), ...] and sort that list by val in O(n log n) time. Loop the first cursor a from 0 to n - 3 and apply the two-pointer technique (initializing b = a + 1 at the start and c = n - 1 at the end of the remaining sorted slice, advancing b rightward when the three-number total is < 0 and pulling c leftward when > 0). Each time the three values add up to 0, sort [idx_a, idx_b, idx_c] so the output indices obey i < j < k, record the triple, and step both b and c inward; the whole procedure runs in O(n^2) time and O(n) auxiliary memory.
  • How can you still find the lexicographically smallest pair in O(n) time if the numbers arrive in a forward-only stream that cannot be traversed backward? Use the left-to-right first_seen approach from Alternative Approaches: keep first_seen[val] as the earliest index of each value seen so far, and maintain best_pair as the lexicographically smallest [first_seen[target - x], j] encountered across the stream. You still cannot emit the final answer until the stream closes (since the very last element could pair with index 0), and it takes O(n) time and O(u) space for u unique values.
  • What changes if the input is not guaranteed to contain a valid pair summing to the target? Agree on a sentinel return value with the caller (such as [] or None). Our right-to-left loop already handles this naturally without extra branches: if needed_val in earliest_after never triggers, best_pair stays [] and is returned directly.

Follow-up questions

Similar questions

More Walmart Labs interview questions

All 38 Walmart Labs questions →