AlgoTales · Roadmap

Two-sum type problems

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A two-sum problem asks for two items that together reach a target. Instead of trying all pairs, you go through the items once and ask for each: has the partner I need already been seen? A hash map answers that instantly.

Practical use cases

  • Web app: Matching a deposit to an invoice pair. An accountant sees a bank deposit of Rs 7,500 and wants the two invoices that together make it. The code goes through invoices one by one, asking a map whether 7,500 minus this amount was already seen. The matching pair is found in a single pass over thousands of invoices.
  • Web app: Gift voucher combos. A shop offers "pick any two items totalling exactly Rs 1,000 with your voucher". For each product added to the list, the page checks a map for the price that completes the sum. Suggestions appear as shoppers browse, without freezing the catalogue.
  • System: Payment reconciliation jobs. Nightly reconciliation tools pair up debits and credits that cancel each other. Remembering amounts already seen in a map means each entry is matched with one lookup. Without it, every debit would be compared with every credit, which can take hours on a busy business day.

The story: The Dance Partner Register

At the school dance, each kid wore a badge with a number. The teacher's rule: two kids can dance together if their numbers add up to the magic number, 9. The hall was crowded and kids arrived one at a time.

The slow way: every new kid walks around the hall and asks everyone, "What's your number?" That is a lot of walking. Mira had a better idea. She sat at the door with a register.

Each arriving kid says their number. Mira computes "9 minus yours", which is the partner they are looking for, and checks the register: "Is that number already signed in?" If yes, pair found! If not, she writes this kid's number in the register for future arrivals. One look-up per kid. That register is a hash map.

How to spot this problem, and where you need it

You need to find two entries whose values combine into a target, such as a sum, difference or a matching pair, and trying every pair becomes far too slow.

Signs you need it

  • The problem says "two numbers that add up to", "pair with difference k" or "find a complement".
  • Your first idea is two loops, each element against every other element, and it crawls on big data.
  • You can say the need as "for this item, which other item completes it?" and the answer is a specific value.

Where to use it in a project

  • Reconciliation screens matching payments with invoices or refunds with orders.
  • Offer and coupon logic where two items must meet a total, or where you need to detect pairs that cancel each other.

The solution

Make an empty map. For each item, work out its partner: target minus the item. Look the partner up in the map. If it is there, you have the pair and can stop. If not, store the current item in the map and move on. You touch each item once and each question is a direct lookup, so you never compare all pairs.

Payoff: Before: 10,000 invoices meant up to 50 million pair checks. After: 10,000 lookups, so the match shows up instantly.

Explain it like I am 8

You are playing a matching game. For each card you pick up, you ask yourself: "What is my missing partner?" Then you peek into a magic notebook that answers "have I seen that card already?" instantly. If yes, you win. If not, you write your card in the notebook and go on.

How it works, step by step

  1. Create an empty register (a hash map): number → where we saw it.
  2. For each number, compute what is missing: need = target - number.
  3. Look in the register. If need is there, we found the pair.
  4. Otherwise sign in. Store this number so later numbers can find it.

The code in four languages

PHP

<?php
function twoSum(array $nums, int $target): ?array {
    $seen = [];                                   // value => index (our register)

    foreach ($nums as $i => $n) {
        $need = $target - $n;                     // who is my partner?
        if (isset($seen[$need])) {
            return [$seen[$need], $i];            // found: both positions
        }
        $seen[$n] = $i;                           // sign in for later kids
    }
    return null;
}

print_r(twoSum([2, 7, 11, 15, 3], 9));            // [0, 1]  (2 + 7)

JavaScript

function twoSum(nums, target) {
  const seen = new Map();                         // value -> index (our register)

  for (let i = 0; i < nums.length; i++) {
    const need = target - nums[i];                // who is my partner?
    if (seen.has(need)) {
      return [seen.get(need), i];                 // found: both positions
    }
    seen.set(nums[i], i);                         // sign in for later kids
  }
  return null;
}

console.log(twoSum([2, 7, 11, 15, 3], 9));        // [0, 1]  (2 + 7)

Java

import java.util.*;

public class Main {
    // Returns the two positions whose values add up to target, or null.
    static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> seen = new HashMap<>();     // value -> index (our register)

        for (int i = 0; i < nums.length; i++) {
            int need = target - nums[i];                  // who is my partner?
            if (seen.containsKey(need)) {
                return new int[]{seen.get(need), i};      // found: both positions
            }
            seen.put(nums[i], i);                         // sign in for later kids
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSum(new int[]{2, 7, 11, 15, 3}, 9)));   // [0, 1]  (2 + 7)
    }
}

Go

package main

import "fmt"

// twoSum returns the two positions whose values add up to target.
func twoSum(nums []int, target int) ([]int, bool) {
	seen := map[int]int{} // value -> index (our register)

	for i, n := range nums {
		need := target - n // who is my partner?
		if j, ok := seen[need]; ok {
			return []int{j, i}, true // found: both positions
		}
		seen[n] = i // sign in for later kids
	}
	return nil, false
}

func main() {
	pos, _ := twoSum([]int{2, 7, 11, 15, 3}, 9)
	fmt.Println(pos) // [0 1]  (2 + 7)
}

Time: O(n) · Extra space: O(n). We trade memory for speed: the register costs space but removes the inner loop (brute force is O(n²)).

Watch out for

  • Adding a number to the register before checking. A number may wrongly pair with itself.
  • Assuming hash maps are always O(1). Terrible hash functions or many collisions can slow them down (a later chapter).

Quick check

  1. What do we look up in the register for number x?
    • x itself
    • target - x
    • target + x
  2. What do we give up to make this fast?
    • Memory
    • Accuracy
    • Readability
  3. Brute force on two-sum takes…
    • O(n²)
    • O(1)
    • O(log n)