Reading history

Meet in the Middle in C

6 min read 1 views

Learn the meet in the middle technique in C: split subset sum into two halves and combine them with sorting and binary search.

Some problems can only be solved by checking every subset. With n items there are 2n subsets: a million for n = 20, but over a trillion for n = 40. Meet in the middle splits the items into two halves of n/2 each. It lists the subsets of each half separately (only about a million each for n = 40), then combines the two lists cleverly with sorting and binary search. The time drops from O(2n) to about O(2n/2 × n).

In this lesson you will learn

  • Brute-force subset sum and its limits
  • Why 2n/2 is so much smaller than 2n
  • Generating all subset sums of a half
  • Combining the halves with sorting and binary search
  • The memory cost and when the technique applies

You should know backtracking, binary search and bitmasks.

Brute Force Subset Sum

#include <stdio.h>

/* Subset sum by brute force: try all 2^n subsets.
   Fine for n = 20 (about a million), hopeless for n = 40 (about a trillion). */
int main(void) {
    int price[] = { 120, 340, 75, 510, 260, 95, 430, 180 };   /* gift prices in taka */
    int n = 8, budget = 950, ways = 0;
    long checked = 0;

    for (unsigned mask = 0; mask < (1u << n); mask++) {
        int sum = 0;
        for (int i = 0; i < n; i++) if (mask & (1u << i)) sum += price[i];
        checked++;
        if (sum == budget) {
            ways++;
            printf("found:");
            for (int i = 0; i < n; i++) if (mask & (1u << i)) printf(" %d", price[i]);
            printf("\n");
        }
    }
    printf("%d way(s) to spend exactly %d; subsets checked: %ld\n", ways, budget, checked);

    for (int k = 10; k <= 40; k += 10)
        printf("n = %d -> 2^n = %.0f subsets, but 2^(n/2) = %.0f per half\n",
               k, (double)(1ull << k), (double)(1ull << (k / 2)));
    return 0;
}

Output

found: 510 260 180
found: 340 75 260 95 180
found: 340 430 180
3 way(s) to spend exactly 950; subsets checked: 256
n = 10 -> 2^n = 1024 subsets, but 2^(n/2) = 32 per half
n = 20 -> 2^n = 1048576 subsets, but 2^(n/2) = 1024 per half
n = 30 -> 2^n = 1073741824 subsets, but 2^(n/2) = 32768 per half
n = 40 -> 2^n = 1099511627776 subsets, but 2^(n/2) = 1048576 per half
  • The problem: which groups of gifts cost exactly 950 taka? Each subset is a bitmask from 0 to 2n – 1, as in the bitmask lesson.
  • For 8 items there are only 256 subsets, so brute force is instant.
  • The table at the end shows the problem: every extra item doubles the work. At n = 40 there are about 1.1 trillion subsets.
  • But each half of 40 items has only about one million subsets. Meet in the middle uses exactly this.

Splitting the Problem in Half

#include <stdio.h>
#include <stdlib.h>

/* Meet in the middle: count subsets of 40 numbers whose sum is exactly T.
   Split into halves A and B (20 each). List all 2^20 subset sums of each half,
   sort B's sums, and for every sum s of A look for T - s in B by binary search. */

static int cmp(const void *x, const void *y) {
    long long a = *(const long long *)x, b = *(const long long *)y;
    return (a > b) - (a < b);
}

/* Fill out[] with all 2^n subset sums of v[0..n-1] */
static void allSums(const long long *v, int n, long long *out) {
    out[0] = 0;
    for (int i = 0, size = 1; i < n; i++, size *= 2)
        for (int j = 0; j < size; j++) out[size + j] = out[j] + v[i];   /* without / with v[i] */
}

/* Number of elements equal to key in a sorted array */
static long long countEqual(const long long *a, long long n, long long key) {
    long long lo = 0, hi = n;
    while (lo < hi) { long long mid = (lo + hi) / 2; if (a[mid] < key) lo = mid + 1; else hi = mid; }
    long long first = lo;
    hi = n;
    while (lo < hi) { long long mid = (lo + hi) / 2; if (a[mid] <= key) lo = mid + 1; else hi = mid; }
    return lo - first;
}

int main(void) {
    enum { N = 40, H = N / 2 };
    long long v[N];
    unsigned seed = 7;
    for (int i = 0; i < N; i++) {                      /* 40 fixed pseudo-random weights */
        seed = seed * 1103515245u + 12345u;
        v[i] = 1 + (seed >> 16) % 1000;
    }
    long long total = 0;
    for (int i = 0; i < N; i++) total += v[i];
    long long T = total / 2;

    long long *A = malloc(sizeof(long long) << H), *B = malloc(sizeof(long long) << H);
    if (!A || !B) return 1;
    allSums(v, H, A);
    allSums(v + H, H, B);
    qsort(B, (size_t)1 << H, sizeof *B, cmp);

    long long ways = 0;
    for (long long i = 0; i < (1LL << H); i++) ways += countEqual(B, 1LL << H, T - A[i]);

    printf("40 numbers, total %lld, target T = %lld\n", total, T);
    printf("subsets with sum exactly T: %lld\n", ways);
    printf("work: 2 x %d sums + sorting, instead of %lld subsets\n", 1 << H, 1LL << N);
    free(A); free(B);
    return 0;
}

Output

40 numbers, total 19892, target T = 9946
subsets with sum exactly T: 237610882
work: 2 x 1048576 sums + sorting, instead of 1099511627776 subsets
  • The 40 numbers are split into half A (first 20) and half B (last 20).
  • allSums lists all 220 subset sums of a half. It builds them by doubling: for each new number, every existing sum appears once without it and once with it.
  • Any subset of all 40 numbers is a subset of A combined with a subset of B. So the total is T exactly when the A-part sums to s and the B-part sums to T - s.
  • After sorting B’s sums, each s from A needs one binary search for T - s. countEqual uses two binary searches to count how many B-sums match, since several subsets can share a sum.
  • The program counts over 237 million matching subsets in well under a second, without listing the trillion subsets one by one.
  • The cost is memory: two arrays of about a million long long values, around 16 MB in total.
MethodTime for n = 40Memory
Check every subset240 ≈ 1.1 trillion stepsTiny
Meet in the middleAbout 2 × 220 × 20 ≈ 42 million steps2 × 220 sums
DP on the sum (if values are small)n × T stepsT + 1 values

Common Mistakes

  1. Using int for sums that can exceed about 2.1 billion. Use long long.
  2. Forgetting the empty subset (sum 0) in each half, which misses answers that use only one half.
  3. Counting only one match per search when several B-subsets have the same sum.
  4. Splitting into uneven halves, such as 10 and 30, which loses most of the benefit.

Practice Exercises

Exercise 1. How many subset sums does each half have for n = 30, and how does that compare with 230?

Show answer

Each half of 15 items has 215 = 32,768 sums. Together that is 65,536 sums, compared with 230 ≈ 1.07 billion subsets.

Exercise 2. Change the method to find the largest subset sum that is at most a budget W.

Show answer

Sort B’s sums. For each sum s in A with s <= W, binary search B for the largest value at most W - s, and keep the best s plus that value. This is the classic way to solve 0/1 knapsack when n is about 40 and the values are too large for a DP table.

Frequently Asked Questions

When should I think of meet in the middle?

When n is around 30 to 45, the answer needs all subsets or combinations, and the problem splits into two independent halves that can be joined with a simple rule, such as “the two sums add up to T”.

Is it related to bidirectional search?

Yes. Bidirectional search in graphs explores from the start and from the goal at the same time and stops when the two searches meet. It uses the same idea of attacking a problem from both ends.

Summary

  • Splitting n items into two halves turns 2n subsets into two lists of 2n/2.
  • Generate every subset sum of each half, sort one list and binary search it.
  • Time falls to about O(2n/2 × n), practical for n up to about 40.
  • The price is memory to store both lists.

Next: Interval Problems in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *