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
Create a hash map value -> index. Iterate, compute complement. If complement in map, return [map[complement], i]. Store current value and index.
Time O(n), Space O(n).
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.
