← Questions
Two sum with the lexicographically smallest index pair
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round, last asked Dec 2025. It tests hash maps and arrays.
Given an integer array and a target, return the pair of distinct indices [i, j] with i < j and nums[i] + nums[j] == target that is lexicographically smallest: the smallest i, and among those the smallest j. The answer must be deterministic, so the first pair a hash map happens to find is not good enough.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
two_sum_smallest(nums: list[int], target: int) -> list[int]—[i, j], or[]when no pair exists. Don't mutatenums.
Example
two_sum_smallest([4, 1, 5, 3, 3], 6) -> [1, 2] # [3, 4] also works, but 1 < 3
two_sum_smallest([1, 4, 6, 100, 200, 9], 10) -> [0, 5] # beats [1, 2]: the left index decides first
two_sum_smallest([2, 2], 4) -> [0, 1]
two_sum_smallest([1, 2, 3], 10) -> []
Constraints
-
0 <= len(nums) <= 2 · 10^5. -
-10^9 <= nums[i], target <= 10^9; use 64-bit arithmetic for sums and complements. - Target expected O(n) time and O(n) extra space.
Clarifying questions
- Is the order "smallest left index first", or "the pair found first while scanning"?
- Can an element pair with itself? (No:
i != j.) - Duplicates allowed?
- Return indices or values?
What a strong answer covers
- Why the usual one-pass hash map gives the pair with the smallest
j, not the smallesti(the second example breaks it). - A correct O(n) approach: map each value to its earliest index, scan
jleft to right and track the best[i, j]byi; or scanifrom the left and, for each, find the smallestj > iholdingtarget - nums[i]using sorted position lists per value. - The sorting alternative: sort
(value, index)pairs, two pointers, and collect candidates while keeping the index tie-break. O(n log n). - Duplicates and a value equal to
target / 2. - Tests: empty, one element, several valid pairs, the counterexample above.
Follow-ups
- Return all pairs, in lexicographic order.
- The array is sorted. Do it in O(1) extra space.
- Return the pair with the smallest
jinstead, and explain how the code changes.
Where it's asked
- Google · Onsite coding · Last asked Dec 202545 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
