Two Sum — Indices Summing to a Target
Company: J.P. Morgan
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's ability to design an efficient array-searching algorithm that maps values to indices under a target-sum constraint. It tests understanding of hash-based lookups versus brute-force pairwise comparison, a foundational data structures and algorithms topic in coding interviews. It is commonly used to assess time-complexity reasoning at an introductory to intermediate practical level.
Constraints
- 2 <= nums.length <= 10^4
- -10^9 <= nums[i] <= 10^9
- -10^9 <= target <= 10^9
- Exactly one valid pair of indices exists.
- The two returned indices must be distinct.
Examples
Input: ([2, 7, 11, 15], 9)
Expected Output: [0, 1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9.
Input: ([3, 2, 4], 6)
Expected Output: [1, 2]
Explanation: nums[1] + nums[2] = 2 + 4 = 6; index 0 cannot pair with itself.
Input: ([3, 3], 6)
Expected Output: [0, 1]
Explanation: Two distinct indices both hold the value 3.
Input: ([-1000000000, 1000000000, 3, 5], 0)
Expected Output: [0, 1]
Explanation: Large opposite-sign values: -1e9 + 1e9 = 0.
Input: ([-3, 4, 3, 90], 0)
Expected Output: [0, 2]
Explanation: Negatives allowed: nums[0] + nums[2] = -3 + 3 = 0.
Input: ([1, 5, 5, 11], 10)
Expected Output: [1, 2]
Explanation: The matching pair uses the two duplicate 5s at distinct indices 1 and 2.
Hints
- A brute-force O(n^2) check of every pair works but is slow for n up to 10^4.
- For each element x, you need to find target - x. A hash map lets you look that up in O(1).
- Scan left to right, storing each value's index as you go. Before storing the current value, check whether its complement was already seen — this naturally guarantees the two indices are distinct.