AlgoTales · Roadmap

Divide and conquer

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

Where you will meet this in real life

Divide and conquer means splitting a big problem into smaller copies of itself, solving each small copy, then joining the answers. It is worth knowing because many fast tools, like sorting and big report builders, rely on it.

Practical use cases

  • Web app: Sorting a million orders in an export. An admin downloads all orders sorted by amount. Comparing every order with every other is far too slow. Splitting the list in half again and again, sorting tiny pieces, and merging them back gives a sorted file in seconds instead of minutes.
  • Web app: Monthly revenue report across many shops. A SaaS dashboard needs one total from 50,000 small shop tables. Instead of one loop on one server, the work is split into chunks, each chunk is totalled separately, and the chunk totals are added. A report that took 40 seconds is ready in about 5. Each worker only handles its own chunk, so adding more workers makes the whole report finish sooner.
  • Web app: Image thumbnails and filters. A photo-upload page applies a filter to big pictures. The image is cut into tiles, each tile is processed on its own, and the results are stitched back together. Large images no longer block the page, because the small tiles are finished one by one.
  • System: MapReduce style big-data jobs. Systems that crunch huge log files split the data across many machines, let each machine summarise its own piece, and then combine those summaries into the final answer. Adding more machines simply means cutting the data into more pieces, so the same program keeps scaling as the logs grow.

The story: The Wedding Card Pile

Mira's cousin was getting married and the family had to write 800 invitation cards by hand. Grandpa Bhaskar sat down and started on card number one. After an hour his hand hurt and the pile had barely moved.

Aunty Meena clapped her hands. "Everyone listen! Split the pile in half. You take 400, I take 400." Then each of them split their share again, and again, until every cousin held just five cards. Five cards is nothing. The whole house was writing at once, and even the little cousins were proudly counting their five cards twice.

The twist came at the end. The finished cards still had to be gathered. Pairs of cousins merged their stacks, then bigger groups merged theirs, until one tidy box reached the printer. Mrs. Sharma, watching from the sofa with a cup of chai, smiled and named the trick: "Divide the big problem, conquer the small pieces, combine the answers. That is divide and conquer."

How to spot this problem, and where you need it

A job is too big to do in one go, but it looks the same at every size, so you could do half of it, then the other half, and combine them.

Signs you need it

  • You can describe the problem as "do the same thing on the left half and right half, then combine".
  • A simple solution compares everything against everything and gets painfully slow as the data doubles.
  • The small cases are trivial (an empty list, one item) and combining two small answers is easy.

Where to use it in a project

  • Sorting or merging large lists in reports, exports and search results shown to users.
  • Splitting a big batch job into chunks that run in parallel on queue workers.
  • Image, audio or large-number processing where separate pieces can be handled independently and joined later.

The solution

Do three things. Divide: cut the input into smaller pieces of the same kind. Conquer: solve each piece the same way, stopping when a piece is so small the answer is obvious. Combine: join the small answers into the answer for the whole. Because the pieces are independent, they can even run on separate workers at the same time.

Payoff: Before: a million-row sort by comparing everything, minutes of work. After: about 20 levels of halving, seconds of work.

Explain it like I am 8

If you have to carry 100 books, ask 10 friends to carry 10 each. A big job becomes many tiny jobs that look exactly like the big one, only smaller. At the end you just put the small answers together.

How it works, step by step

  1. Base case: if the piece is tiny (one item), answer it directly.
  2. Divide: cut the problem into smaller pieces of the same kind, usually two halves.
  3. Conquer: solve each piece by calling the very same function (recursion, remember the nesting dolls).
  4. Combine: merge the little answers into the answer for the bigger piece. For "biggest score" combine is just max.
  5. Famous users: merge sort, quick sort and binary search are all divide and conquer.

The code in four languages

PHP

<?php
// Return [biggest, total] of scores[lo..hi] using divide and conquer.
function solve(array $s, int $lo, int $hi): array {
    if ($lo === $hi) return [$s[$lo], $s[$lo]];     // base case: one score
    $mid = intdiv($lo + $hi, 2);
    [$maxL, $sumL] = solve($s, $lo, $mid);           // conquer the left half
    [$maxR, $sumR] = solve($s, $mid + 1, $hi);       // conquer the right half
    return [max($maxL, $maxR), $sumL + $sumR];       // combine
}

$scores = [3, 8, 2, 9, 4, 6, 1, 7];
[$best, $total] = solve($scores, 0, count($scores) - 1);
echo "Biggest: $best, total: $total\n";               // Biggest: 9, total: 40

JavaScript

// Return [biggest, total] of scores[lo..hi] using divide and conquer.
function solve(s, lo, hi) {
  if (lo === hi) return [s[lo], s[lo]];        // base case: one score
  const mid = Math.floor((lo + hi) / 2);
  const [maxL, sumL] = solve(s, lo, mid);      // conquer the left half
  const [maxR, sumR] = solve(s, mid + 1, hi);  // conquer the right half
  return [Math.max(maxL, maxR), sumL + sumR];  // combine
}

const scores = [3, 8, 2, 9, 4, 6, 1, 7];
const [best, total] = solve(scores, 0, scores.length - 1);
console.log('Biggest: ' + best + ', total: ' + total);   // Biggest: 9, total: 40

Java

public class Main {
    // Return {biggest, total} of s[lo..hi] using divide and conquer.
    static int[] solve(int[] s, int lo, int hi) {
        if (lo == hi) return new int[]{s[lo], s[lo]};      // base case: one score
        int mid = (lo + hi) / 2;
        int[] left = solve(s, lo, mid);                    // conquer the left half
        int[] right = solve(s, mid + 1, hi);               // conquer the right half
        return new int[]{Math.max(left[0], right[0]), left[1] + right[1]};   // combine
    }

    public static void main(String[] args) {
        int[] scores = {3, 8, 2, 9, 4, 6, 1, 7};
        int[] result = solve(scores, 0, scores.length - 1);
        System.out.println("Biggest: " + result[0] + ", total: " + result[1]);   // Biggest: 9, total: 40
    }
}

Go

package main

import "fmt"

// solve returns (biggest, total) of s[lo..hi] using divide and conquer.
func solve(s []int, lo, hi int) (int, int) {
	if lo == hi { // base case: one score
		return s[lo], s[lo]
	}
	mid := (lo + hi) / 2
	maxL, sumL := solve(s, lo, mid)     // conquer the left half
	maxR, sumR := solve(s, mid+1, hi)   // conquer the right half
	return max(maxL, maxR), sumL + sumR // combine
}

func main() {
	scores := []int{3, 8, 2, 9, 4, 6, 1, 7}
	best, total := solve(scores, 0, len(scores)-1)
	fmt.Printf("Biggest: %d, total: %d\n", best, total) // Biggest: 9, total: 40
}

Time: O(n) here (O(n log n) for merge sort) · Extra space: O(log n). The pile splits about log n times; the cost depends on how much work "combine" does at each level.

Watch out for

  • Forgetting the base case, so the pieces never stop shrinking and the stack overflows.
  • Splitting into pieces that overlap or leave a gap (off-by-one in mid and mid + 1).
  • Using divide and conquer when the pieces are not independent. Then you repeat work and want dynamic programming instead.

Quick check

  1. What are the three moves of divide and conquer?
    • Divide, conquer, combine
    • Sort, search, stop
    • Loop, count, print
  2. What is the base case for "biggest of a list"?
    • An empty program
    • A list with one item
    • A list of 100 items
  3. Which famous sort is divide and conquer?
    • Bubble sort
    • Counting every card
    • Merge sort