Two Sum: find two indices whose values add up to a target.
Problem
Given an int array and a target, return indices i != j with nums[i] + nums[j] == target. Assume exactly one solution.
Approach
Brute force checks every pair in O(n²). Instead, scan once and store each value's index in a HashMap; for each element, check whether target - value was already seen. One pass, O(n). If the array were sorted, two pointers from both ends would solve it in O(n) with O(1) extra space.
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
class TwoSum {
static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(target - nums[i]);
if (j != null) return new int[] {j, i};
seen.put(nums[i], i);
}
throw new IllegalArgumentException("no solution");
}
// Variant: sorted input, O(1) extra space
static int[] twoSumSorted(int[] sorted, int target) {
int lo = 0, hi = sorted.length - 1;
while (lo < hi) {
int sum = sorted[lo] + sorted[hi];
if (sum == target) return new int[] {lo, hi};
if (sum < target) lo++; else hi--;
}
throw new IllegalArgumentException("no solution");
}
public static void main(String[] args) {
System.out.println(Arrays.toString(twoSum(new int[] {2, 7, 11, 15}, 9))); // [0, 1]
System.out.println(Arrays.toString(twoSumSorted(new int[] {1, 3, 4, 6, 9}, 10))); // [0, 4]
}
}Complexity
HashMap version: O(n) time, O(n) space. Two-pointer version: O(n) time, O(1) space (O(n log n) if you must sort first).
Follow-up questions interviewers ask
Try answering each one before you open it.
How would you solve 3Sum (all unique triplets summing to zero)?
Sort the array, then for each index i run the two-pointer search on the rest for -nums[i], skipping duplicate values for i, lo and hi to avoid duplicate triplets. O(n²) time, O(1) extra space apart from the output.