Lesson 6 of 164
Find Two Numbers That Add Up to k
Given an array of integers nums and a target k, return the indices of two different elements whose values add up to k. Return an empty array if there's no such pair.
LeetCode: 1. Two Sum
Example 1
Input: nums = [2, 7, 11, 15], k = 9
Output: [0, 1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9Example 2
Input: nums = [3, 2, 4], k = 6
Output: [1, 2]
Explanation: 2 + 4 = 6. Index 0 can't be used twice (3 + 3).Brute force: check every pair
Try every pair of indices (i, j) with i < j, and return the first pair whose values add up to k. Starting j at i + 1 means each pair is checked once and an element is never paired with itself.
import java.util.Arrays;
public class Main {
// Returns {i, j} with i < j, or an empty array when no pair exists.
static int[] twoSum(int[] nums, int k) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == k) return new int[]{i, j};
}
}
return new int[0];
}
public static void main(String[] args) {
System.out.println(Arrays.toString(twoSum(new int[]{2, 7, 11, 15}, 9)));
System.out.println(Arrays.toString(twoSum(new int[]{3, 2, 4}, 6)));
System.out.println(Arrays.toString(twoSum(new int[]{1, 2}, 10)));
}
}[0, 1]
[1, 2]
[]Time: O(n²), with n(n-1)/2 pairs checked in the worst case. Space: O(1).
Better: sort, then use two pointers
If the array were sorted, two pointers could find the pair in one pass:
- Put
leftat the smallest value andrightat the largest. - If their sum is too small, the only way to increase it is to move
leftright. - If their sum is too large, move
rightleft.
Sorting loses the original positions, so we sort an array of indices by their values instead of sorting the values.
import java.util.Arrays;
import java.util.Comparator;
public class Main {
static int[] twoSum(int[] nums, int k) {
Integer[] idx = new Integer[nums.length]; // boxed, because sorting with a comparator needs objects
for (int i = 0; i < idx.length; i++) idx[i] = i;
Arrays.sort(idx, Comparator.comparingInt(i -> nums[i]));
int left = 0, right = idx.length;
while (left + 1 < right) {
int sum = nums[idx[left]] + nums[idx[right - 1]];
if (sum == k) {
int a = idx[left], b = idx[right - 1];
return new int[]{Math.min(a, b), Math.max(a, b)};
} else if (sum < k) {
left++;
} else {
right--;
}
}
return new int[0];
}
public static void main(String[] args) {
System.out.println(Arrays.toString(twoSum(new int[]{2, 7, 11, 15}, 9)));
System.out.println(Arrays.toString(twoSum(new int[]{3, 2, 4}, 6)));
System.out.println(Arrays.toString(twoSum(new int[]{1, 2}, 10)));
}
}[0, 1]
[1, 2]
[]Time: O(n log n) for the sort, plus O(n) for the scan. Space: O(n) for the index list. If the input is already sorted, or only the values are needed, this is O(n) time and O(1) space.
Optimal: one pass with a HashMap
For each value x, the partner we need is k - x. As we scan left to right, a HashMap stores every value seen so far and its index. If the partner is already in the map, we have the answer. Otherwise, we store x and move on.
Walkthrough with nums = [2, 7, 11, 15], k = 9:
| i | nums[i] | needed partner (9 - x) | in map? | map after |
|---|---|---|---|---|
| 0 | 2 | 7 | no | {2: 0} |
| 1 | 7 | 2 | yes, at index 0 | return (0, 1) |
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Main {
static int[] twoSum(int[] nums, int k) {
Map<Integer, Integer> seen = new HashMap<>(); // value -> index
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(k - nums[i]);
if (j != null) return new int[]{j, i};
seen.put(nums[i], i);
}
return new int[0];
}
public static void main(String[] args) {
System.out.println(Arrays.toString(twoSum(new int[]{2, 7, 11, 15}, 9)));
System.out.println(Arrays.toString(twoSum(new int[]{3, 2, 4}, 6)));
System.out.println(Arrays.toString(twoSum(new int[]{3, 3}, 6)));
System.out.println(Arrays.toString(twoSum(new int[]{1, 2}, 10)));
}
}[0, 1]
[1, 2]
[0, 1]
[]Time: O(n): one pass with O(1) expected map operations. Space: O(n) for the map.
Looking up the partner before inserting the current value is what keeps an element from pairing with itself. In [3, 2, 4] with k = 6, index 0 looks for 3 while the map is still empty. With [3, 3], the second 3 finds the first one, which is a valid pair of different indices.
Edge cases
- No pair exists: every approach returns an empty array.
- Negative numbers and zero: all three approaches handle them.
- Overflow:
intarithmetic wraps silently, sok - xoverflows for extreme values likek = Integer.MIN_VALUEandx = 1, andnums[i] + nums[j]can wrap into a false match. Compute inlongif the input range allows that. - Several valid pairs: the problem accepts any one of them. The HashMap version returns the pair whose second element comes first.
