Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Problem Description
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Approach
We can use a Hash Map to store the numbers we have seen so far and their indices. For each number x, we check if target - x exists in the map. If it does, we have found the pair.
Solution
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<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);
}
throw new IllegalArgumentException("No two sum solution");
}
}