AlgoTales · Roadmap

Divide and conquer

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

Where you will meet this in real life

Divide and conquer cuts a big job into halves, solves each half the same way, and combines the results. It is the idea behind merge sort, quick sort and the way big data jobs are shared among many machines.

Practical use cases

  • Web app: Counting words across thousands of files. A document-search site counts word frequencies over 50,000 uploaded files. The files are split into groups of 2,500, each group is counted on its own queue worker, and the partial counts are merged at the end. The job drops from hours to minutes.
  • Web app: Sorting a big export by date. An admin exports a million rows sorted by date. Merge sort splits the rows, sorts the small parts and merges them back, so the file is ready quickly and predictably.
  • Web app: Ledger totals across many branches. A finance system adds up thousands of ledger pages by totalling halves of the pile and then adding the two totals. Each half can be done on a different worker. Each worker totals its own pages, and a final step adds only a few numbers.
  • System: Signal and image processing, MapReduce. Audio and image tools break signals into parts, and MapReduce systems send chunks to many machines before combining the results. Adding more machines simply means cutting the data into more pieces and merging at the end.

The story: Raju Splits the Ledger

Raju kept a ledger with nine days of profit and loss. Some days he lost money: −2, −3, −1, −5. Others he made some: 1, 4, 2, 1, 4. Kabir asked: "Which run of days in a row was the best?" Raju started adding every possible stretch. For nine days it took forever; for a whole year it would take his lifetime.

Mira grabbed a ruler and drew a line in the middle: "Let’s split the ledger into two halves. Hand the left half to Aarav and the right half to Zoya. They answer the same question, just for a smaller ledger. If they get stuck they split again with their own friends."

But Mira spotted the catch: "The best stretch might straddle the cut: some days from the left and some from the right." That one is easy to check, because it must start at the middle and grow outwards. So: best of left, best of right, best crossing the middle, pick the biggest. Answer: 6.

That is divide and conquer: split the problem, solve the halves the same way, combine the results. The smell: the problem works on a range or array, halves are independent, and there is a clean way to merge the two answers. Merge sort, quick sort and binary search are all cousins.

How to spot this problem, and where you need it

A big job takes too long when done as one lump, but it can be cut into independent pieces whose answers are easy to combine.

Signs you need it

  • The job is "do X over all N things" and doing half the things gives half the answer.
  • A simple solution compares everything with everything, and the time quadruples when data doubles.
  • You can run chunks on several workers or queue jobs in parallel.

Where to use it in a project

  • Sorting and merging big lists and exports so users can download them quickly.
  • Batch reports that can be split by date range, shop or file and run on separate workers.
  • Parallel processing with Laravel queues, workers or background jobs.

The solution

Divide the input into two or more smaller parts of the same kind. Solve each part with the same method, stopping when a part is tiny and the answer is obvious. Then combine the part answers (merge sorted halves, add totals, join counts). If the parts do not depend on each other, run them in parallel.

Payoff: Before: one worker counting 50,000 files in about 2 hours. After: 20 workers, each finishing its share in about 6 minutes.

Explain it like I am 8

You have 100 exam papers to grade. Instead of grading alone, you give 50 to one friend and 50 to another, and they split theirs again. Everyone grades just a few papers, and at the end the small piles of marks are added together.

How it works, step by step

  1. Spot the clue: the input can be cut in halves, and the halves can be solved independently (no need to look at the other half to solve one).
  2. Base case: a tiny piece (one element) is answered directly.
  3. Divide: cut in the middle and solve left and right with the same function.
  4. Combine: merge the two answers, and watch for things that cross the cut (the tricky bit).
  5. Check the cost: halving gives about log n levels of work, which often turns a slow n² method into n log n.

The code in four languages

PHP

<?php
// Classic: "Maximum Subarray" using divide and conquer.
function bestStretch(array $a, int $lo, int $hi): int {
    if ($lo === $hi) return $a[$lo];              // base case: one day
    $mid = intdiv($lo + $hi, 2);

    $left  = bestStretch($a, $lo, $mid);          // conquer left half
    $right = bestStretch($a, $mid + 1, $hi);      // conquer right half

    // stretch crossing the cut: grow left from mid, grow right from mid+1
    $sum = 0; $leftEdge = PHP_INT_MIN;
    for ($i = $mid; $i >= $lo; $i--) { $sum += $a[$i]; $leftEdge = max($leftEdge, $sum); }
    $sum = 0; $rightEdge = PHP_INT_MIN;
    for ($i = $mid + 1; $i <= $hi; $i++) { $sum += $a[$i]; $rightEdge = max($rightEdge, $sum); }

    return max($left, $right, $leftEdge + $rightEdge);   // combine
}
$profit = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
echo bestStretch($profit, 0, count($profit) - 1);        // 6

JavaScript

// Classic: "Maximum Subarray" using divide and conquer.
function bestStretch(a, lo, hi) {
  if (lo === hi) return a[lo];                    // base case: one day
  const mid = Math.floor((lo + hi) / 2);

  const left = bestStretch(a, lo, mid);           // conquer left half
  const right = bestStretch(a, mid + 1, hi);      // conquer right half

  // stretch crossing the cut: grow left from mid, grow right from mid+1
  let sum = 0, leftEdge = -Infinity;
  for (let i = mid; i >= lo; i--) { sum += a[i]; leftEdge = Math.max(leftEdge, sum); }
  sum = 0;
  let rightEdge = -Infinity;
  for (let i = mid + 1; i <= hi; i++) { sum += a[i]; rightEdge = Math.max(rightEdge, sum); }

  return Math.max(left, right, leftEdge + rightEdge);   // combine
}
const profit = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
console.log(bestStretch(profit, 0, profit.length - 1));  // 6

Java

public class Main {
    // Classic: "Maximum Subarray" using divide and conquer.
    static int bestStretch(int[] a, int lo, int hi) {
        if (lo == hi) return a[lo];                   // base case: one day
        int mid = lo + (hi - lo) / 2;

        int left = bestStretch(a, lo, mid);           // conquer left half
        int right = bestStretch(a, mid + 1, hi);      // conquer right half

        // stretch crossing the cut: grow left from mid, grow right from mid+1
        int sum = 0, leftEdge = Integer.MIN_VALUE;
        for (int i = mid; i >= lo; i--) { sum += a[i]; leftEdge = Math.max(leftEdge, sum); }
        sum = 0;
        int rightEdge = Integer.MIN_VALUE;
        for (int i = mid + 1; i <= hi; i++) { sum += a[i]; rightEdge = Math.max(rightEdge, sum); }

        return Math.max(Math.max(left, right), leftEdge + rightEdge);   // combine
    }

    public static void main(String[] args) {
        int[] profit = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println(bestStretch(profit, 0, profit.length - 1));  // 6
    }
}

Go

package main

import (
	"fmt"
	"math"
)

// bestStretch is the classic "Maximum Subarray" using divide and conquer.
func bestStretch(a []int, lo, hi int) int {
	if lo == hi {
		return a[lo] // base case: one day
	}
	mid := lo + (hi-lo)/2

	left := bestStretch(a, lo, mid)    // conquer left half
	right := bestStretch(a, mid+1, hi) // conquer right half

	// stretch crossing the cut: grow left from mid, grow right from mid+1
	sum, leftEdge := 0, math.MinInt
	for i := mid; i >= lo; i-- {
		sum += a[i]
		leftEdge = max(leftEdge, sum)
	}
	sum = 0
	rightEdge := math.MinInt
	for i := mid + 1; i <= hi; i++ {
		sum += a[i]
		rightEdge = max(rightEdge, sum)
	}

	return max(left, right, leftEdge+rightEdge) // combine
}

func main() {
	profit := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}
	fmt.Println(bestStretch(profit, 0, len(profit)-1)) // 6
}

Time: O(n log n) · Extra space: O(log n). Halving gives about log n levels; each level does O(n) work on the crossing checks. (Kadane's one-pass method does this one in O(n), but this lesson shows the pattern.)

Watch out for

  • Forgetting the crossing case. Only taking the best of left and right misses answers that straddle the middle.
  • Missing the base case, or a mid calculation that makes a half empty so the recursion never ends.
  • Using divide and conquer when the halves depend on each other. Then you need dynamic programming or another approach.

Quick check

  1. Which is the main shape of divide and conquer?
    • Choose, explore, undo
    • Sort, then sweep
    • Remember and reuse
    • Split, solve halves, combine
  2. Why do we check a stretch "crossing the cut"?
    • To make the code longer
    • To avoid recursion
    • Because the best answer may use days from both halves
    • Because the halves are unsorted
  3. Which classic algorithm is divide and conquer?
    • Merge sort
    • Bubble sort
    • Linear search
    • Counting sort