Two Sum
💻 Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here.Revision notes
Two Sum (online-test style) + Two Sum II
Video: “Two Sum” on LearnWithKiriti (Kodee and Mr. Tock). Arrays series, episode 16. LeetCode 1, Easy, plus LeetCode 167 (Two Sum II, input sorted). Taught as an online coding test: three rounds of 5:00 each (15 minutes), thinking time counts, and the fast answer grows out of the slow one.
Find the positions of two numbers in nums that add up to target. Exactly one answer; a number can’t pair with itself.
nums = [2, 7, 11, 15], target = 9 -> [0, 1] (2 + 7 = 9)
| Folder | Approach | Time | Extra space |
|---|---|---|---|
Brute-EveryPair/ |
first from 0, second after it, check every pair |
O(n²) | O(1) |
Optimal-HashMap/ |
One pass: need = target - nums[second]; if need is in seen return, else remember nums[second] -> second |
O(n) | O(n) |
Sorted-TwoPointers-LC167/ |
Sorted input: left at the start, right at the end; too small → left up, too big → right down; 1-based answer |
O(n) | O(1) |
Rebuild it
Ask for the partner. Check, then remember. Sorted? Squeeze both ends.
- The brute’s inner loop only asks one thing: is
target - mesomewhere before me? Remember what you’ve seen instead of scanning back. - A hash map lookup opens one drawer: the number picks its own drawer through a tiny formula. Nothing is scanned.
- Check BEFORE you store: with
[3, 3], target 6, storing first makes the first 3 find itself. - Duplicates are harmless: the old position already had its chance before the map overwrote it.
- Sorted: if
nums[left] + nums[right]is too small,nums[left]with ANY partner left is too small, so drop left (mirror for too big). The squeeze never skips the answer. - Don’t sort LeetCode 1: sorting scrambles the positions (and costs n log n). A yes/no “is there a pair?” can sort and squeeze.
- The ladder: 3Sum = fix one number + Two Sum on the rest; 4Sum = fix two + Two Sum.
Practise it on learnwithkiriti.com (notes, code in 4 languages, the Memory Pairs game, a mock interview with Mr. Tock, Shelf Bot animates your own code), or next to the video in the Kodee Practice Chrome extension (link in the video description).
See the pseudocode.md in each folder. Every program was compiled, run and tested.
Brute: Every Pair
R1 Brute: try every pair
for first = 0 to n-1:
for second = first+1 to n-1:
if nums[first] + nums[second] == target:
return [first, second]
return []
Why second starts at first + 1: no number pairs with itself, and each pair is tried once.
Check on eight cards [11, 4, 15, 9, 2, 13, 7, 6], target 9: 11 with all seven partners, then 4, 15 and 9 find nothing; 2 + 13 no, 2 + 7 = 9 → [4, 6] after 24 checks.
Cost: n × (n − 1) ÷ 2 checks. 20 numbers: 19 + 18 + … + 1 = 190 tries. O(n²) time, O(1) extra space.
import java.util.*;
public class TwoSumBrute {
static int[] twoSumBrute(int[] nums, int target) {
for (int first = 0; first < nums.length; first++) {
for (int second = first + 1; second < nums.length; second++) {
if (nums[first] + nums[second] == target) {
return new int[] {first, second};
}
}
}
return new int[] {};
}
static String show(Object o) {
if (o instanceof int[]) return java.util.Arrays.toString((int[]) o);
if (o instanceof long[]) return java.util.Arrays.toString((long[]) o);
if (o instanceof boolean[]) return java.util.Arrays.toString((boolean[]) o);
if (o instanceof Object[]) return java.util.Arrays.deepToString((Object[]) o);
return String.valueOf(o);
}
public static void main(String[] args) {
System.out.println(show(twoSumBrute(new int[]{2, 7, 11, 15}, 9)));
System.out.println(show(twoSumBrute(new int[]{3, 2, 4}, 6)));
System.out.println(show(twoSumBrute(new int[]{3, 3}, 6)));
System.out.println(show(twoSumBrute(new int[]{11, 15, 2, 7}, 9)));
System.out.println(show(twoSumBrute(new int[]{11, 4, 15, 9, 2, 13, 7, 6}, 9)));
System.out.println(show(twoSumBrute(new int[]{-3, 4, 3, 90}, 0)));
}
}#include <bits/stdc++.h>
using namespace std;
vector<int> twoSumBrute(vector<int>& nums, int target) {
for (int first = 0; first < nums.size(); first++) {
for (int second = first + 1; second < nums.size(); second++) {
if (nums[first] + nums[second] == target) {
return {first, second};
}
}
}
return {};
}
string show(int value) { return to_string(value); }
string show(long long value) { return to_string(value); }
string show(bool value) { return value ? "true" : "false"; }
string show(const string& value) { return "\"" + value + "\""; }
template <typename T> string show(const vector<T>& values) {
string text = "[";
for (size_t index = 0; index < values.size(); index++) {
text += (index ? ", " : "") + show(values[index]);
}
return text + "]";
}
int main() {
{ auto arg0 = vector<int>{2, 7, 11, 15}; auto arg1 = 9; cout << show(twoSumBrute(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{3, 2, 4}; auto arg1 = 6; cout << show(twoSumBrute(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{3, 3}; auto arg1 = 6; cout << show(twoSumBrute(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{11, 15, 2, 7}; auto arg1 = 9; cout << show(twoSumBrute(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{11, 4, 15, 9, 2, 13, 7, 6}; auto arg1 = 9; cout << show(twoSumBrute(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{-3, 4, 3, 90}; auto arg1 = 0; cout << show(twoSumBrute(arg0, arg1)) << endl; }
return 0;
}import json
def twoSumBrute(nums, target):
for first in range(len(nums)):
for second in range(first + 1, len(nums)):
if nums[first] + nums[second] == target:
return [first, second]
return []
if __name__ == "__main__":
print(json.dumps(twoSumBrute([2, 7, 11, 15], 9)).replace(',', ', '))
print(json.dumps(twoSumBrute([3, 2, 4], 6)).replace(',', ', '))
print(json.dumps(twoSumBrute([3, 3], 6)).replace(',', ', '))
print(json.dumps(twoSumBrute([11, 15, 2, 7], 9)).replace(',', ', '))
print(json.dumps(twoSumBrute([11, 4, 15, 9, 2, 13, 7, 6], 9)).replace(',', ', '))
print(json.dumps(twoSumBrute([-3, 4, 3, 90], 0)).replace(',', ', '))function twoSumBrute(nums, target) {
for (let first = 0; first < nums.length; first++) {
for (let second = first + 1; second < nums.length; second++) {
if (nums[first] + nums[second] === target) {
return [first, second];
}
}
}
return [];
}
console.log(JSON.stringify(twoSumBrute([2, 7, 11, 15], 9)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSumBrute([3, 2, 4], 6)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSumBrute([3, 3], 6)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSumBrute([11, 15, 2, 7], 9)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSumBrute([11, 4, 15, 9, 2, 13, 7, 6], 9)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSumBrute([-3, 4, 3, 90], 0)).replace(/,/g, ', '));Optimal: Hash Map
R2 Optimal (LeetCode 1): one pass with a hash map
seen = empty map (number -> position)
for second = 0 to n-1:
need = target - nums[second]
if need in seen: return [seen[need], second]
seen[nums[second]] = second
return []
Derivation: from the second number’s side, the brute’s inner loop only asks “is target minus me somewhere before me?”. Scanning back is the slow part, so remember what you’ve seen.
Check FIRST, then remember: with [3, 3], target 6, remembering first makes the first 3 find itself.
Check on eight cards [11, 4, 15, 9, 2, 13, 7, 6], target 9: 11, 4, 15 and 9 ask and are remembered; 2 needs 7, remember; 13, nothing; 7 needs 2: seen[2] = 4 → [4, 6], seven checks.
Why a hash map is O(1): the key goes through a formula (hashing) to one slot of an array; the same key always gives the same slot, so nothing is scanned. Two keys can share a slot (a collision, e.g. 3 and 19 with 16 slots), so each slot keeps a short list; a good formula keeps the lists tiny, so a lookup is O(1) on average.
Names: Java java.util.HashMap (fully qualified, no import), Python dict, C++ unordered_map, JavaScript Map.
Complexity: O(n) time (at most 20 checks for 20 numbers), O(n) extra space.
import java.util.*;
public class TwoSum {
static int[] twoSum(int[] nums, int target) {
java.util.HashMap<Integer, Integer> seen = new java.util.HashMap<>();
for (int second = 0; second < nums.length; second++) {
int need = target - nums[second];
if (seen.containsKey(need)) {
return new int[] {seen.get(need), second};
}
seen.put(nums[second], second);
}
return new int[] {};
}
static String show(Object o) {
if (o instanceof int[]) return java.util.Arrays.toString((int[]) o);
if (o instanceof long[]) return java.util.Arrays.toString((long[]) o);
if (o instanceof boolean[]) return java.util.Arrays.toString((boolean[]) o);
if (o instanceof Object[]) return java.util.Arrays.deepToString((Object[]) o);
return String.valueOf(o);
}
public static void main(String[] args) {
System.out.println(show(twoSum(new int[]{2, 7, 11, 15}, 9)));
System.out.println(show(twoSum(new int[]{3, 2, 4}, 6)));
System.out.println(show(twoSum(new int[]{3, 3}, 6)));
System.out.println(show(twoSum(new int[]{11, 15, 2, 7}, 9)));
System.out.println(show(twoSum(new int[]{11, 4, 15, 9, 2, 13, 7, 6}, 9)));
System.out.println(show(twoSum(new int[]{-3, 4, 3, 90}, 0)));
}
}#include <bits/stdc++.h>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> seen;
for (int second = 0; second < nums.size(); second++) {
int need = target - nums[second];
if (seen.count(need)) {
return {seen[need], second};
}
seen[nums[second]] = second;
}
return {};
}
string show(int value) { return to_string(value); }
string show(long long value) { return to_string(value); }
string show(bool value) { return value ? "true" : "false"; }
string show(const string& value) { return "\"" + value + "\""; }
template <typename T> string show(const vector<T>& values) {
string text = "[";
for (size_t index = 0; index < values.size(); index++) {
text += (index ? ", " : "") + show(values[index]);
}
return text + "]";
}
int main() {
{ auto arg0 = vector<int>{2, 7, 11, 15}; auto arg1 = 9; cout << show(twoSum(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{3, 2, 4}; auto arg1 = 6; cout << show(twoSum(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{3, 3}; auto arg1 = 6; cout << show(twoSum(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{11, 15, 2, 7}; auto arg1 = 9; cout << show(twoSum(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{11, 4, 15, 9, 2, 13, 7, 6}; auto arg1 = 9; cout << show(twoSum(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{-3, 4, 3, 90}; auto arg1 = 0; cout << show(twoSum(arg0, arg1)) << endl; }
return 0;
}import json
def twoSum(nums, target):
seen = {}
for second in range(len(nums)):
need = target - nums[second]
if need in seen:
return [seen[need], second]
seen[nums[second]] = second
return []
if __name__ == "__main__":
print(json.dumps(twoSum([2, 7, 11, 15], 9)).replace(',', ', '))
print(json.dumps(twoSum([3, 2, 4], 6)).replace(',', ', '))
print(json.dumps(twoSum([3, 3], 6)).replace(',', ', '))
print(json.dumps(twoSum([11, 15, 2, 7], 9)).replace(',', ', '))
print(json.dumps(twoSum([11, 4, 15, 9, 2, 13, 7, 6], 9)).replace(',', ', '))
print(json.dumps(twoSum([-3, 4, 3, 90], 0)).replace(',', ', '))function twoSum(nums, target) {
const seen = new Map();
for (let second = 0; second < nums.length; second++) {
const need = target - nums[second];
if (seen.has(need)) {
return [seen.get(need), second];
}
seen.set(nums[second], second);
}
return [];
}
console.log(JSON.stringify(twoSum([2, 7, 11, 15], 9)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSum([3, 2, 4], 6)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSum([3, 3], 6)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSum([11, 15, 2, 7], 9)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSum([11, 4, 15, 9, 2, 13, 7, 6], 9)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSum([-3, 4, 3, 90], 0)).replace(/,/g, ', '));Sorted: Two Pointers LC167
R3 Sorted (LeetCode 167): two pointers, O(1) space, 1-based answer
left = 0; right = n-1
while left < right:
sum = nums[left] + nums[right]
if sum == target: return [left + 1, right + 1]
if sum < target: left = left + 1
else: right = right - 1
return []
Proof it never skips the answer: if the sum is too small, nums[left] plus ANY number still in range is at most that sum, so nums[left] can’t be in the answer: drop left. Too big: drop right, by the mirror argument. Check on eight sorted cards [1, 2, 4, 5, 10, 13, 14, 16], target 9: 1 + 16, 1 + 14, 1 + 13, 1 + 10 too big (right moves in each time), 1 + 5 = 6 too small (left up), 2 + 5 = 7 too small (left up), 4 + 5 = 9 → [3, 4] (1-based). Why not sort LeetCode 1: sorting scrambles the positions it asks for, and costs n log n. Complexity: O(n) time, O(1) extra space.
import java.util.*;
public class TwoSumSorted {
static int[] twoSumSorted(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) {
return new int[] {left + 1, right + 1};
}
if (sum < target) {
left++;
} else {
right--;
}
}
return new int[] {};
}
static String show(Object o) {
if (o instanceof int[]) return java.util.Arrays.toString((int[]) o);
if (o instanceof long[]) return java.util.Arrays.toString((long[]) o);
if (o instanceof boolean[]) return java.util.Arrays.toString((boolean[]) o);
if (o instanceof Object[]) return java.util.Arrays.deepToString((Object[]) o);
return String.valueOf(o);
}
public static void main(String[] args) {
System.out.println(show(twoSumSorted(new int[]{2, 7, 11, 15}, 9)));
System.out.println(show(twoSumSorted(new int[]{2, 3, 4}, 6)));
System.out.println(show(twoSumSorted(new int[]{-1, 0}, -1)));
System.out.println(show(twoSumSorted(new int[]{2, 3, 6, 9}, 9)));
System.out.println(show(twoSumSorted(new int[]{1, 2, 4, 5, 10, 13, 14, 16}, 9)));
}
}#include <bits/stdc++.h>
using namespace std;
vector<int> twoSumSorted(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) {
return {left + 1, right + 1};
}
if (sum < target) {
left++;
} else {
right--;
}
}
return {};
}
string show(int value) { return to_string(value); }
string show(long long value) { return to_string(value); }
string show(bool value) { return value ? "true" : "false"; }
string show(const string& value) { return "\"" + value + "\""; }
template <typename T> string show(const vector<T>& values) {
string text = "[";
for (size_t index = 0; index < values.size(); index++) {
text += (index ? ", " : "") + show(values[index]);
}
return text + "]";
}
int main() {
{ auto arg0 = vector<int>{2, 7, 11, 15}; auto arg1 = 9; cout << show(twoSumSorted(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{2, 3, 4}; auto arg1 = 6; cout << show(twoSumSorted(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{-1, 0}; auto arg1 = -1; cout << show(twoSumSorted(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{2, 3, 6, 9}; auto arg1 = 9; cout << show(twoSumSorted(arg0, arg1)) << endl; }
{ auto arg0 = vector<int>{1, 2, 4, 5, 10, 13, 14, 16}; auto arg1 = 9; cout << show(twoSumSorted(arg0, arg1)) << endl; }
return 0;
}import json
def twoSumSorted(nums, target):
left = 0
right = len(nums) - 1
while left < right:
sum = nums[left] + nums[right]
if sum == target:
return [left + 1, right + 1]
if sum < target:
left += 1
else:
right -= 1
return []
if __name__ == "__main__":
print(json.dumps(twoSumSorted([2, 7, 11, 15], 9)).replace(',', ', '))
print(json.dumps(twoSumSorted([2, 3, 4], 6)).replace(',', ', '))
print(json.dumps(twoSumSorted([-1, 0], -1)).replace(',', ', '))
print(json.dumps(twoSumSorted([2, 3, 6, 9], 9)).replace(',', ', '))
print(json.dumps(twoSumSorted([1, 2, 4, 5, 10, 13, 14, 16], 9)).replace(',', ', '))function twoSumSorted(nums, target) {
let left = 0;
let right = nums.length - 1;
while (left < right) {
const sum = nums[left] + nums[right];
if (sum === target) {
return [left + 1, right + 1];
}
if (sum < target) {
left++;
} else {
right--;
}
}
return [];
}
console.log(JSON.stringify(twoSumSorted([2, 7, 11, 15], 9)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSumSorted([2, 3, 4], 6)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSumSorted([-1, 0], -1)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSumSorted([2, 3, 6, 9], 9)).replace(/,/g, ', '));
console.log(JSON.stringify(twoSumSorted([1, 2, 4, 5, 10, 13, 14, 16], 9)).replace(/,/g, ', '));