Solving the Two Sum Problem in Java
Given an array of integers nums and an integer target, return the indices of two numbers that add up to the target value.
Example:
Input: nums = [3, 4, 2], target = 6
Output: [1, 2]
Explanation: nums[1] + nums[2] equals 6
Approaches
-
Brute Force Method:
- Iterate through each element and check every other element for a matching sum
- Time complexity: O(n²)
-
Hash Map Optimization:
- Use a hash map to store values and indices as we iterate
- Check if the complement (target - current value) exists in the map
- Time complexity: O(n)
Java Implementations
Brute Force Solution:
public int[] findTwoSum(int[] numbers, int sumTarget) {
for (int first = 0; first < numbers.length; first++) {
for (int second = first + 1; second < numbers.length; second++) {
if (numbers[first] + numbers[second] == sumTarget) {
return new int[]{first, second};
}
}
}
return new int[0];
}
Optimized Hash Map Solution:
import java.util.HashMap;
public int[] optimizedTwoSum(int[] numbers, int sumTarget) {
HashMap<Integer, Integer> valueIndexMap = new HashMap<>();
for (int current = 0; current < numbers.length; current++) {
int complement = sumTarget - numbers[current];
if (valueIndexMap.containsKey(complement)) {
return new int[]{valueIndexMap.get(complement), current};
}
valueIndexMap.put(numbers[current], current);
}
return new int[0];
}