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.
Sample Input: nums = [2,7,11,15], target = 9
Expected Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Constraints
2 <= nums.length <= 104-109 <= nums[i] <= 109-109 <= target <= 109- Only one valid answer exists.
How We Solve This
- Use a HashMap to store numbers we have seen and their indices.
- Iterate through the array one number at a time.
- For each number, calculate the required
complement(target-current number). - Check if the
complementexists in the HashMap. If it does, we have found our solution. - If not, add the current number and its index to the HashMap.
Edge Cases to Consider
Negative Numbers
Input:
[-3, 4, 3, 90]Target:
0Output:
[0, 2]The algorithm correctly handles negative numbers.
Zeros in Input
Input:
[0, 4, 3, 0]Target:
0Output:
[0, 3]It can find pairs of zeros if they exist.
Pair at Start/End
Input:
[11, 2, 7, 15]Target:
9Output:
[1, 2]The pair can be anywhere in the array.