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 < jis strictly required). - Whenever two or more valid index pairs produce
target, choose the lexicographically earliest pair: minimize the first indexiabove all else, and if multiple candidates share that smallesti, minimize the second indexj. - 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^9for every0 <= k < len(nums)-2 * 10^9 <= target <= 2 * 10^9- At least one pair
(i, j)with0 <= i < j < len(nums)satisfiesnums[i] + nums[j] == target.
Step-by-step walkthrough
Understand lexicographic tie-breaking on index pairs
Given an unsorted integer list
numsand an integertarget, we must return 0-based indices[i, j]withi < jandnums[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 indexifirst, and only usejto break ties wheniis 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!Brute force tries pairs in exact lexicographic order
A nested loop with
ifrom0ton - 1andjfromi + 1ton - 1visits 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 checksn * (n - 1) / 2pairs — roughly5 * 10^9operations forn = 100,000, which is far too slow.Why the standard left-to-right Two Sum breaks tie-breaking
In the textbook
O(n)Two Sum, you scanjfrom 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
joptimizes for the smallestj, whereas our problem demands the smallestifirst!Key insight: sweep from right to left
Suppose we fix
iand look only to the right ofi(indicesi + 1 .. n - 1). Which partnerj > idoesiwant? The smallest index afteriwheretarget - nums[i]appears!If we sweep
ibackward fromlen(nums) - 1down to0and maintain a dictionaryearliest_aftermapping each value to its smallest index seen to the right ofi, 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- Guarantee
i < j: Look upneeded_val = target - nums[i]before insertingnums[i], soearliest_aftercontains only indices strictly greater thani. - Smallest
jfor a giveni: After the lookup, unconditionally assignearliest_after[current_val] = i. Becauseiis smaller than any index we visited earlier, overwriting always keeps the leftmost copy in the suffix! - Smallest
ioverall: Keep scanning all the way toi = 0without returning early. Every timeneeded_val in earliest_after, overwritebest_pair = [i, earliest_after[needed_val]]— becauseistrictly decreases on each iteration, every newly found pair has a strictly smallerithan 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- Guarantee
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, overwritingearliest_after[4] = 2replaced index3with the nearer index2, soi = 0paired withj = 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 = 1we temporarily record[1, 2], and ati = 0we find[0, 3], overwritingbest_pairand returning[0, 3].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 thenindices once fromn - 1down to0, performing one subtraction, oneO(1)average-time dictionary lookup (needed_val in earliest_after), and oneO(1)average-time dictionary write (earliest_after[current_val] = i). - Space:
O(n). In the worst case where allnnumbers innumsare distinct,earliest_afterstoresnkey-value pairs.
Edge cases
- Duplicate values that pair together (
[-2, -2],target = -4): Ati = 1,earliest_afterbecomes{-2: 1}; ati = 0, we look up-2before overwritingearliest_after[-2] = 0, cleanly producing[0, 1]. - Single copy of
target / 2([4, -1, 9],target = 8): Because lookup happens before insertion,nums[0] = 4does not see itself inearliest_after, avoiding the illegal self-pair[0, 0]and returning[1, 2]. - Multiple valid partners
jfor the besti([6, 1, 4, 4],target = 10): As the scan passesi = 3and theni = 2,earliest_after[4]updates from3to2, soi = 0picks[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 ati = 0overwrites[1, 2]found ati = 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 sotarget - current_valnever 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 smallesti! You must finish scanning down toi = 0. - Inserting
earliest_after[current_val] = ibefore checkingif needed_val in earliest_after:: Whenever2 * nums[i] == target,iimmediately pairs with itself and returns[i, i], violatingi < 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)jinstead 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 smallestjrather than the smallesti.
Alternative approaches
- Left-to-right streaming scan keeping earliest occurrences (
O(n)time,O(n)space): Scanjfrom0ton - 1storing only the first (smallest) index where each value appeared (if val not in first_seen: first_seen[val] = j). Whenevertarget - nums[j]is infirst_seen, formcandidate = [first_seen[target - nums[j]], j]and keep the minimumcandidate(still without returning early!). Because the globally optimal[i*, j*]must use the first occurrence ofnums[i*](otherwise an earlier copy would give an even smalleri), 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 testi = 0, 1, ...from left to right and binary-search (bisect_right) for the first partner index> i, returning on the very firstithat 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 byvalinO(n log n)time. Loop the first cursorafrom0ton - 3and apply the two-pointer technique (initializingb = a + 1at the start andc = n - 1at the end of the remaining sorted slice, advancingbrightward when the three-number total is< 0and pullingcleftward when> 0). Each time the three values add up to0, sort[idx_a, idx_b, idx_c]so the output indices obeyi < j < k, record the triple, and step bothbandcinward; the whole procedure runs inO(n^2)time andO(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_seenapproach from Alternative Approaches: keepfirst_seen[val]as the earliest index of each value seen so far, and maintainbest_pairas 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 index0), and it takesO(n)time andO(u)space foruunique 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
[]orNone). Our right-to-left loop already handles this naturally without extra branches: ifneeded_val in earliest_afternever triggers,best_pairstays[]and is returned directly.
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?
- 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?
- What changes if the input is not guaranteed to contain a valid pair summing to the target?
Similar questions
- Validate Properly Nested Bracket Delimiters
- Days Needed for Pesticide Row to Stabilize
- Minimum Conference Rooms Needed
- Counting Distinct Coin Combinations
- Earliest Unique Character Index
- Matching Index Pairs in Sorted Arrays
More Walmart Labs interview questions
- Minimum Bottleneck Path in a Graph Medium
- Leadership Scenarios on Persuasion, Data, Outages, and Ethics Medium
- Navigating Setbacks and Small Talk in a Hiring Manager Chat Medium Pro
- High-Throughput Multi-Seller E-Commerce Catalog Architecture Medium Pro
- Grounded Multi-Turn Agentic Search System Easy Pro
- Dynamic Half-Open Interval Coverage Tracker Hard Pro
- Cross-Team Technical Disagreement and Execution Alignment Easy Pro
- Shortest All-Talent Subarray From Each Start Hard Pro
- Spring Boot & Thymeleaf Multi-Page Form Architecture Medium Pro
- Validate Properly Nested Bracket Delimiters Medium Pro