AlgoTales · Roadmap

Meet in the middle

Advanced · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Meet in the middle splits a problem with too many combinations into two halves, solves each half separately, and then matches the two sets of answers. It turns an impossible amount of trying into something a laptop can finish.

Practical use cases

  • Web app: Gift-box builder that hits an exact budget. A shopping site lets a user pick 40 items to match a gift voucher of exactly 2,000 rupees. Trying every combination of 40 items is more than a trillion options. Splitting into two groups of 20, listing sums for each, and matching pairs needs only about a million sums, so the suggestion appears quickly.
  • Web app: Expense-splitting app finding a perfect split. A group-expense app wants to know if a set of 36 bills can be split so two people pay exactly the same. Computing sums of each half of the bills and checking for a matching pair answers it in under a second. Instead of trying billions of splits, the app only builds two small lists and matches them.
  • Web app: Puzzle game solver. A web puzzle game must tell whether a board can be solved. Searching from the start and from the goal and meeting in between explores far fewer positions than going all the way from one side. The hint or solve button therefore replies within a second, even on a hard board.
  • System: Cryptanalysis of double encryption. Some attacks on double encryption work by trying all keys for the first lock forward and all keys for the second lock backward, then looking for a match in the middle, turning a two-key search into roughly the cost of one. A search that looked like it needed trillions of attempts becomes two much smaller searches, so it finishes in a few seconds.

The story: Two Shelves, One Weight

Aarav ran the kirana store near the railway station. Every evening a customer asked for something odd: "Give me exactly 9 kg of rice, but I only want whole packets, no opening them." Aarav tried combinations in his head: this one plus that one, no... this plus that plus another, no...

With 6 packets that is fine. But the wholesale godown had 40 packets. Trying every group of packets means over a trillion possibilities. The shop would close before he finished.

Mira had a clever idea. "Uncle, imagine a curtain in the middle of the shelf. List what the left packets can weigh together. List what the right packets can weigh together. Each list has only a million entries. Then, for every left weight, just look up whether the missing weight sits in the right list."

Two small lists meeting in the middle turned a trillion into a couple of million. The name stuck: meet in the middle.

How to spot this problem, and where you need it

You must pick from about 30 to 45 items to hit an exact target, and trying every combination would take years, but trying half of the items is easy.

Signs you need it

  • The problem has around 30 to 40 items with "choose some, skip some" and a target sum, so trying every combination is far too many.
  • Dynamic programming does not work because the values or the target are huge numbers.
  • You can search from both the start and the goal of a puzzle, and each direction alone is too deep.

Where to use it in a project

  • A voucher, bundle or budget matcher that must hit an exact total using many available items.
  • A bill-splitting or load-balancing feature where two groups must end up with equal totals.
  • A puzzle or route solver where both the start and the goal are known and can be searched from.

The solution

Split the items into two halves. For each half, list every possible sum (a half of 20 items gives about a million sums). Sort one list. For each sum in the other list, look up the amount needed to reach the target using a quick search or hash. When a pair matches, you have found a full solution built from both halves.

Payoff: Before: more than a trillion combinations for 40 items. After: about two million sums and some lookups, done in a second or two.

Explain it like I am 8

Two kids dig a tunnel from opposite ends of a hill. Each digs only half the way, and they shake hands in the middle. Together they finish much faster than one kid digging the whole hill.

How it works, step by step

  1. Split the items into two halves (about n/2 each).
  2. List all subset sums of each half. Half the items means far fewer subsets: 2n/2 instead of 2n.
  3. Store one list in a set (or sort it) so look-ups are fast.
  4. For each sum s in the other list, look for target − s. If it exists, the two halves together make the target.
  5. Great when n is around 30 to 40: too big for brute force, too awkward for DP.

The code in four languages

PHP

<?php
// Every total you can make from a small list of packets (include "take nothing" = 0).
function allSums(array $items): array {
    $n = count($items);
    $sums = [];
    for ($mask = 0; $mask < (1 << $n); $mask++) {   // each mask = one choice of packets
        $s = 0;
        for ($i = 0; $i < $n; $i++) {
            if ($mask >> $i & 1) $s += $items[$i];
        }
        $sums[] = $s;
    }
    return $sums;
}

function canMake(array $items, int $target): bool {
    $half = intdiv(count($items), 2);
    $leftSums  = allSums(array_slice($items, 0, $half));
    $rightSet  = array_flip(allSums(array_slice($items, $half)));   // fast look-up
    foreach ($leftSums as $s) {
        if (isset($rightSet[$target - $s])) return true;            // the missing piece exists
    }
    return false;
}

$packets = [3, 34, 4, 12, 5, 2];
echo canMake($packets, 9) ? "Yes" : "No", "\n";    // Yes (4 + 5)
echo canMake($packets, 30) ? "Yes" : "No", "\n";   // No

JavaScript

// Every total you can make from a small list of packets (include "take nothing" = 0).
function allSums(items) {
  const n = items.length, sums = [];
  for (let mask = 0; mask < (1 << n); mask++) {   // each mask = one choice of packets
    let s = 0;
    for (let i = 0; i < n; i++) {
      if (mask >> i & 1) s += items[i];
    }
    sums.push(s);
  }
  return sums;
}

function canMake(items, target) {
  const half = Math.floor(items.length / 2);
  const leftSums = allSums(items.slice(0, half));
  const rightSet = new Set(allSums(items.slice(half)));   // fast look-up
  for (const s of leftSums) {
    if (rightSet.has(target - s)) return true;            // the missing piece exists
  }
  return false;
}

const packets = [3, 34, 4, 12, 5, 2];
console.log(canMake(packets, 9) ? 'Yes' : 'No');    // Yes (4 + 5)
console.log(canMake(packets, 30) ? 'Yes' : 'No');   // No

Java

import java.util.*;

public class Main {
    // Every total you can make from a small list of packets (include "take nothing" = 0).
    static List<Integer> allSums(int[] items) {
        int n = items.length;
        List<Integer> sums = new ArrayList<>();
        for (int mask = 0; mask < (1 << n); mask++) {      // each mask = one choice of packets
            int s = 0;
            for (int i = 0; i < n; i++) {
                if ((mask >> i & 1) == 1) s += items[i];
            }
            sums.add(s);
        }
        return sums;
    }

    static boolean canMake(int[] items, int target) {
        int half = items.length / 2;
        List<Integer> leftSums = allSums(Arrays.copyOfRange(items, 0, half));
        Set<Integer> rightSet = new HashSet<>(allSums(Arrays.copyOfRange(items, half, items.length)));   // fast look-up
        for (int s : leftSums) {
            if (rightSet.contains(target - s)) return true;    // the missing piece exists
        }
        return false;
    }

    public static void main(String[] args) {
        int[] packets = {3, 34, 4, 12, 5, 2};
        System.out.println(canMake(packets, 9) ? "Yes" : "No");    // Yes (4 + 5)
        System.out.println(canMake(packets, 30) ? "Yes" : "No");   // No
    }
}

Go

package main

import "fmt"

// allSums lists every total you can make from a small list of packets (include "take nothing" = 0).
func allSums(items []int) []int {
	n := len(items)
	var sums []int
	for mask := 0; mask < 1<<n; mask++ { // each mask = one choice of packets
		s := 0
		for i := 0; i < n; i++ {
			if mask>>i&1 == 1 {
				s += items[i]
			}
		}
		sums = append(sums, s)
	}
	return sums
}

func canMake(items []int, target int) bool {
	half := len(items) / 2
	leftSums := allSums(items[:half])
	rightSet := map[int]bool{} // fast look-up
	for _, s := range allSums(items[half:]) {
		rightSet[s] = true
	}
	for _, s := range leftSums {
		if rightSet[target-s] { // the missing piece exists
			return true
		}
	}
	return false
}

func yesNo(ok bool) string {
	if ok {
		return "Yes"
	}
	return "No"
}

func main() {
	packets := []int{3, 34, 4, 12, 5, 2}
	fmt.Println(yesNo(canMake(packets, 9)))  // Yes (4 + 5)
	fmt.Println(yesNo(canMake(packets, 30))) // No
}

Time: O(2^(n/2) · n) · Extra space: O(2^(n/2)). Far better than 2^n: for 40 items it is about a million steps instead of a trillion.

Watch out for

  • Forgetting the empty choice (sum 0). Then answers that use only one half are missed.
  • Scanning the right list for every left sum instead of using a set or sorted list. That throws the speed-up away.
  • Expecting it to work for 100 items. Half of 100 is still far too many subsets.

Quick check

  1. Why split into two halves?
    • Each half has far fewer subsets than the whole
    • To sort the numbers
    • To avoid using loops
  2. For a left sum of 3 and a target of 9, what do we look for on the right?
    • 9
    • 6
    • 12
  3. What makes the look-up step fast?
    • Recursion
    • Bubble sort
    • A set or hash map of the right sums