LearnWithKiriti

Two Sum

Easy LeetCode 1 ↗ GitHub ↗
💻 Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here. New: mock interview with Mr. Tock. Explain your approach out loud, he pushes you to improve it, then you code it. You get a scorecard at the end. 🎮 Play Memory Pairs: a mini-game built on this problem. Works on your phone too. Pass Submit to unlock every round.
Play
On this page
  1. Revision notes
  2. Brute: Every Pair
  3. Optimal: Hash Map
  4. Sorted: Two Pointers LC167

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 - me somewhere 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

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.

TwoSumBrute.java
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)));
    }
}
optimal

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.

TwoSum.java
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)));
    }
}
other

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.

TwoSumSorted.java
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)));
    }
}