Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. **Examples:** ```typescript twoSum([2, 7, 11, 15], 9) // [0, 1] twoSum([3, 2, 4], 6) // [1, 2] twoSum([3, 3], 6) // [0, 1] ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(n)
- Space complexity: O(n)
We iterate through the array of length n once. Looking up and inserting values in a hash table takes O(1) on average, resulting in overall O(n) linear runtime.
Follow-Up Questions Interviewers Ask About Two Sum
- If the input array is already sorted, can you achieve O(1) space complexity?
Yes! If the array is sorted, you can use the two-pointer technique: initialize left at 0 and right at end. If sum is too small, left++; if too large, right--. This eliminates the need for a Map and runs in O(1) auxiliary space. - Why prefer Map over an Object literal in JavaScript for this problem?
Map supports numeric keys directly without string coercion, provides faster and guaranteed constant-time lookups and insertions, and prevents collisions with inherited prototype properties. - How would you handle duplicate elements or finding ALL unique pairs that sum to the target?
Sort the array first (or use a frequency hash set). When iterating with two pointers, skip duplicate values by incrementing or decrementing pointers until a new number is encountered.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.