You are given an array of integers and a target integer. Find two numbers in the array that add up to the target. Return the indices of these two numbers. You may assume that exactly one solution exists, and you may not use the same element twice. The answer can be returned in any order.
The brute force approach uses two nested loops to check every pair, running in O(n²). A hash map solves it in O(n) time: iterate through the array, for each element calculate the complement (target minus current value). If the complement exists in the hash map, return the current index and the complement's index. Otherwise, store the current value and its index in the hash map.
This is the most well-known hash table problem and appears in almost every coding interview.
Edge cases include negative numbers, zero, and duplicate values. The hash map approach handles all of these correctly because it stores the first occurrence of each value, ensuring that each element is used at most once.
Example Input & Output
2+4=6
2+7=9
3+3=6
Algorithm Flow
Solution Approach
Use a hash set to track numbers seen so far. For each element, check if the complement (target - current) exists in the set. If it does, return true. Otherwise, add the current element to the set and continue.
The complement approach works because if a + b = target, then b = target - a. By storing previously seen numbers in a hash set, we can check if the required complement has already been encountered in O(1) time per element.
Time complexity is O(n), space complexity is O(n) for the hash set.
Best Answers
import java.util.*;
class Solution {
public int[] solution(int[] nums, int target) {
Map<Integer,Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int comp = target - nums[i];
if (seen.containsKey(comp)) return new int[]{seen.get(comp), i};
seen.put(nums[i], i);
}
return new int[]{};
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
