← 返回 walmartlabs 的题目列表Two Sum with Smallest-Indices Tiebreak (+ 3 Sum Follow-up)
类型:qbank
Given an unsorted array and a target sum, return the indices `(i, j)` of any two elements summing to the target. If multiple pairs exist, return the one with the smallest `i`; on ties, the smallest `j`. Verbal follow-up extends the problem to 3-sum with duplicate removal.
Requirements
Input: nums: int[], target: int.
Return (i, j) with i < j such that nums[i] + nums[j] == target. Among all valid pairs, prefer the one with the smallest i; among those, prefer the smallest j.
Return a sentinel (e.g. [-1, -1] or empty) if no pair exists.
Follow-up (verbal): return all unique triples (a, b, c) such that nums[a] + nums[b] + nums[c] == 0, with no duplicate triples by value. Describe the algorithm but write it only if time permits.
Examples
nums = [3, 2, 4, 3, 1], target = 5
Valid pairs: (0,1)=3+2, (0,4)=3+1, (1,3)=2+3, (3,4)=3+1
Answer: (0,1) — smallest i, then smallest j.
Notes
A single left-to-right scan with a HashMap<value, firstIndex> produces the desired tiebreak naturally: when scanning index j, look up target - nums[j]. If found, the stored index is the smallest possible i (because we only store the first occurrence of each value). Return immediately on the first hit and j is the smallest possible second index for that pair.
The variant that confused candidates was the wording "if there are equal i, return smaller j". With i < j enforced, this collapses to "return the first pair found by left-to-right scan," but it pays to restate this back to the interviewer before coding.
For the 3-sum follow-up, the canonical solution sorts in O(n log n), then for each i runs a two-pointer scan over the suffix. Skip duplicates at every level (if (i > 0 && nums[i] == nums[i-1]) continue; and equivalent skips for left / right after recording a hit). Total time O(n²).
The interviewer in this round defaulted to value-based deduplication for 3-sum (i.e. unique triples by value, not by index set) and asked for the algorithm verbally before requiring code.
Preparation
Drill the one-pass hashmap form until you can write it without thinking; the round graded heavily on running compiled code with the given test cases on HackerRank.
Practice articulating the tiebreak invariant in one sentence ("first occurrence wins because we record values left-to-right") — this saves three to four minutes of back-and-forth.
For 3-sum, rehearse the dedup logic carefully; the most common drop is skipping duplicates on i but not on left / right after recording a triple.
Be ready to discuss the 3-sum complexity and why hashmap-based 3-sum is harder to dedup than the sort + two-pointer form.