Two Sum
EasyNeetCode 150Top Interview 150 Arrays & HashingAccentureAmazonBloombergGoogleHCLInfosysProblem
Given a list of integers nums and an integer target, find two different positions
whose values add up to target.
Return the two indices, smaller one first. You may assume exactly one such pair exists, and you may not use the same position twice.
Constraints
- 2 ≤ nums.length ≤ 10⁴
- −10⁹ ≤ nums[i], target ≤ 10⁹
- Exactly one valid pair exists
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(n)
Time: Each number is visited once, and the map lookup and insert are O(1).
Space: In the worst case the map stores almost every number before the pair appears.
For each number, the partner it needs is target minus that number. Keep a map of numbers already passed, with their indices. If the partner is in the map, we are done. Otherwise store this number and move on. Checking before storing stops a number from pairing with itself.