Implement lexicographically smallest Two Sum
Company: Walmart Labs
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates array manipulation, index-level reasoning, and algorithmic efficiency for locating pair sums under lexicographic tie-breaking, testing attention to ordering constraints and correct index selection.
Constraints
- 2 <= len(nums) <= 2 * 10^5
- -10^9 <= nums[i], target <= 10^9
- `nums` is unsorted
- At least one valid pair exists
Examples
Input: ([2, 7, 11, 15], 9)
Expected Output: [0, 1]
Explanation: `nums[0] + nums[1] = 2 + 7 = 9`, and this is the only valid pair.
Input: ([1, 4, 5, 3, 2], 6)
Expected Output: [0, 2]
Explanation: Valid pairs are `[0, 2]` (1 + 5) and `[1, 4]` (4 + 2). The pair `[0, 2]` is lexicographically smaller because it has the smaller first index.
Input: ([3, 3], 6)
Expected Output: [0, 1]
Explanation: This is the smallest possible array length with a valid answer. The only pair is `[0, 1]`.
Input: ([0, -1, 2, -3, 1], -2)
Expected Output: [3, 4]
Explanation: `nums[3] + nums[4] = -3 + 1 = -2`. No earlier valid pair exists.
Input: ([5, 1, 5, 1], 6)
Expected Output: [0, 1]
Explanation: There are multiple valid pairs: `[0, 1]`, `[0, 3]`, `[1, 2]`, and `[2, 3]`. The lexicographically smallest is `[0, 1]`.
Input: ([4, 6, 1, 3, 5, 2], 7)
Expected Output: [0, 3]
Explanation: Valid pairs include `[1, 2]` (6 + 1), `[0, 3]` (4 + 3), and `[4, 5]` (5 + 2). Even though `[1, 2]` appears earlier during a left-to-right scan, `[0, 3]` is the correct answer because it has the smaller first index.
Hints
- Use a hash map from value to its first occurrence index so you can check whether the needed complement has appeared before in O(1) time.
- Do not stop at the first valid pair you find. Keep comparing candidates using lexicographic order: smaller `i` first, then smaller `j`.