1Two Sum Problem – Find two numbers in an array that add up to a given target.
EasyProblem Statement
Given an array of integers nums and an integer target, return the 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.
Example:
Constraints:
- 2 ≤ nums.length ≤ 10⁴
- -10⁹ ≤ nums[i] ≤ 10⁹
- -10⁹ ≤ target ≤ 10⁹
- Only one valid answer exists
The Solution:
Use a hash map (dictionary) to store numbers you've seen along with their indices. For each number, check if the complement (target - current number) exists in the hash map. If it does, you've found your pair. If not, add the current number to the hash map and continue. This way, you only need to pass through the array once.
Steps:
- Create an empty hash map to store {value: index} pairs
- Loop through the array with index i
- Calculate complement = target - nums[i]
- Check if complement exists in the hash map
- If yes, return [hash_map[complement], i]
- If no, store nums[i] with its index in the hash map
- Continue to the next element
Time: O(n) - visit each element once
Space: O(n) - hash map stores up to n elements
def twoSum(nums, target):
hash_map = {}
for i in range(len(nums)):
complement = target - nums[i]
if complement in hash_map:
return [hash_map[complement], i]
hash_map[nums[i]] = i
return []
# Test
nums = [2, 7, 11, 15]
target = 9
result = twoSum(nums, target)
print(f"Output: {result}")Output:
Output: [0, 1]
import java.util.HashMap;
import java.util.Arrays;
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] {map.get(complement), i};
}
map.put(nums[i], i);
}
return new int[] {};
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] result = sol.twoSum(nums, target);
System.out.println("Output: " + Arrays.toString(result));
}
}Output:
Output: [0, 1]