Divide and conquer applications
The standard divide and conquer algorithms of the syllabus with their recurrences: fast exponentiation, maximum subarray, counting inversions, Karatsuba multiplication, Strassen matrix multiplication, closest pair of points and linear-time selection by the median of medians; each with the idea, the recurrence, the solution and the points where GATE asks.
Why it exists
The last page defined the method; this page applies it to the problems that appear in courses and exams, and for each one answers the same three questions: how is the problem cut, how are the answers combined, and what recurrence results. Several of these algorithms are famous because they beat an obvious method by changing the exponent (multiplying two -digit numbers in instead of steps, two matrices in instead of ), and GATE tests exactly those exponents.
Prerequisites
You need the paradigm and the Master theorem (divide and conquer).
Precise definitions
All problems below are solved with recurrences of the form (divide and conquer), apart from selection. The new definitions:
Maximum subarray. Given numbers (some negative), find over non-empty contiguous ranges.
Inversion. A pair with (see elementary sorts).
Closest pair. Given points in the plane, find two distinct points at the smallest Euclidean distance.
Selection (order statistic). Find the -th smallest of keys; the median is .
How it works
The table collects the recurrences of the algorithms of this and the previous pages. Each Master-form row was decided by the decision procedure of the recurrence page and confirmed by evaluating the recurrence.
Divide and conquer algorithms and their recurrences: start
Computed by a script, not typed| recurrence | solution | how it is solved | |
|---|---|---|---|
| Binary search | |||
| Maximum and minimum | |||
| Merge sort | |||
| Quicksort, balanced split | |||
| Maximum subarray (divide and conquer) | |||
| Counting inversions (merge sort based) | |||
| Closest pair of points | |||
| Karatsuba multiplication | |||
| Strassen matrix multiplication | |||
| Fast exponentiation x^n | |||
| Quicksort, worst split | |||
| Linear-time selection (median of medians) |
Step 0
The standard divide and conquer algorithms, the recurrence of each and its solution. The Master form rows were decided by the decision procedure of scripts/algo_lib.py; the two other rows were confirmed by evaluating the recurrence.
Fast exponentiation
To compute : if the answer is ; otherwise compute , square it, and multiply by once more if is odd. Since for even and for odd , this is correct. One subproblem of half the size and a constant amount of work: , so multiplications instead of the of a loop. Exactly squarings and extra multiplications are made, at most in total. The program counts them (modulo a prime-sized number to keep the values small) and checks the result against the loop.
#include <stdio.h>
#define MOD 1000003ULL
static long mults;
/* x^n mod MOD by repeated squaring, n >= 1: T(n) = T(n/2) + (1 or 2) multiplications */
static unsigned long long power(unsigned long long x, unsigned n) {
if (n == 1) return x % MOD;
unsigned long long h = power(x, n / 2);
unsigned long long r = h * h % MOD; /* the squaring */
mults++;
if (n % 2 == 1) { /* an odd exponent needs one more multiplication */
r = r * x % MOD;
mults++;
}
return r;
}
int main(void) {
unsigned ns[] = {2, 7, 8, 100, 1000, 1023, 1024, 1000000};
printf("%8s %6s %8s %s\n", "n", "mults", "n - 1", "same result as the loop");
for (int t = 0; t < 8; t++) {
unsigned n = ns[t];
mults = 0;
unsigned long long fast = power(3, n);
unsigned long long slow = 3;
for (unsigned i = 1; i < n; i++) slow = slow * 3 % MOD;
printf("%8u %6ld %8u %s\n", n, mults, n - 1, fast == slow ? "yes" : "NO");
}
return 0;
} n mults n - 1 same result as the loop
2 1 1 yes
7 4 6 yes
8 3 7 yes
100 8 99 yes
1000 14 999 yes
1023 18 1022 yes
1024 10 1023 yes
1000000 25 999999 yesFor : squarings and extra multiplications (six 1 bits minus one) give the of the table. The worst case for a given length is (all bits one): needs .
Maximum subarray
Cut the array in the middle. The best range is entirely in the left half, entirely in the right half, or crosses the middle. The first two are the recursive calls. The best crossing range is the best suffix of the left half plus the best prefix of the right half, found by two scans of total length . So . (A single left-to-right scan that keeps the best sum ending at the current position, Kadane's algorithm, solves it in and is a dynamic programming idea.)
Counting inversions
Run merge sort and count while merging (merge sort). When the merge takes a key from the right half, it is smaller than all keys still waiting in the left half, so it forms one inversion with each of them: add the number of keys left in the left half. Inversions inside a half are counted by the recursive calls, so the total is left + right + crossing. The merge is linear: , against for checking all pairs. For split as and : the left half has inversions, the right , and pairs cross ( and each exceed and ), in total , the number found earlier by counting directly.
Karatsuba multiplication
Write two -digit numbers as and , with (or ). Then The schoolbook method makes four half-size products, . Karatsuba's idea: with , the middle term is a third half-size product, so only three products are needed, plus additions and shifts that cost :
Strassen's matrix multiplication
Split each matrix into four blocks. The block formulas for need eight block products, . Strassen found seven:
It uses additions or subtractions of half-size matrices (each ), so
The identities were checked symbolically, and a C program (not printed here; it is in scripts/gen-algo-sort-traces.py) multiplied random integer matrices both ways: the products agree, the number of scalar multiplications is for the classical method and for Strassen's, .
Scalar multiplications: classical versus Strassen: start
Computed by a script, not typed| n | classical | Strassen (measured) | 8^k | 7^k | Strassen / classical |
|---|---|---|---|---|---|
| 2 | |||||
| 4 | |||||
| 8 | |||||
| 16 | |||||
| 32 |
Step 0
Two n-by-n integer matrices (n = 2^k) are multiplied the classical way and by Strassen's recursion down to 1-by-1 blocks. Scalar multiplications are counted, and the two products are compared.
Because the saving is a constant factor with a larger constant in the additions, Strassen's method pays off only for large matrices. The formulas never swap the two factors of a product, so they are valid for blocks, which do not commute.
Closest pair of points
Sort the points by once (and by once). Cut by a vertical line into two halves of points; solve each; let be the smaller of the two closest distances. A closer pair must have one point on each side, and both points are within of the line, so only the strip of points within of the line matters. Sort the strip points by and compare each with the next few points in order: a point has at most later points with a -difference below . Such points lie in a rectangle of width and height above it, made of two squares (one on each side of the line); the points on one side are at least apart, so each square holds at most of them, at most points including the point itself. So the combine step is linear, if the points are kept in order by merging (as merge sort does): If instead the strip is sorted from scratch at every level, the combine step is and the total becomes . A concrete case: the points on the left and on the right. Both halves have closest distance (pairs – and –). The strip around holds the points with from to ; sorted by they are ; the very first neighbours already give – at distance , the overall answer (checked against all pairs).
Selection in linear time
Quickselect partitions around a pivot and recurses on the side that contains the -th key: expected time, worst case (quicksort). The median of medians makes the pivot good: split the keys into groups of , find each group's median (constant time per group), find the median of these medians recursively, and use as the pivot. At least about keys are smaller than and as many are larger (half of the group medians are at least , and each of those groups has three keys at least ), so the recursive call on one side has at most keys: Since the solution is (each level's total size shrinks by a constant factor, so the work is a geometric series dominated by the top). With groups of the fractions would be , the recurrence solves to , and no linear bound follows; groups of also work. The constants are large, so quickselect is used in practice.
Worked examples
EX 1Count the multiplications of x to the power n
Easy: four squarings (). : squarings and extra multiplications: in all (). A loop needs . For an exponent with bits the method uses between and multiplications. The recurrence is (or ), .
EX 2Count the multiplications of Strassen
EasyFor matrices: multiplications (instead of ). For : . For (): against , about of the classical count. The exponent: .
EX 3Maximum subarray by divide and conquer
MediumArray . Left half : its best range is . Right half : best is . Crossing the middle: the best suffix of the left half ends at and is (sums of suffixes: ); the best prefix of the right half is (prefix sums: ). Crossing total: , the maximum of : the answer is , the range .
EX 4Karatsuba on a small example
Medium, , : , , , . , , , so the middle term is . Then . Three multiplications of two-digit numbers instead of four.
EX 5Read the exponent from the idea
GATE level(a) Multiplying two -bit numbers with three recursive half-size multiplications and linear extra work: . (b) An algorithm multiplies matrices by 7 recursive calls on half-size matrices and additional work: . (c) The same with 8 calls: (the leaves dominate). (d) Closest pair where the strip is sorted afresh at every level: (the logarithmic extension of case 2). (e) Counting inversions by checking all pairs: ; by the merge sort method: .
Cheat box
Cheat box
- Fast exponentiation: , ; squarings (ones of ) multiplications.
- Maximum subarray: best of left, right, crossing; , (Kadane: ).
- Inversions: merge sort, add the keys left in the left half when taking from the right; .
- Karatsuba: products, , .
- Strassen: products and additions, , ; classical .
- Closest pair: strip of width sorted by , at most neighbours each; if order is kept, if the strip is re-sorted.
- Selection: quickselect expected , worst ; median of medians (groups of ) worst case : .
Traps and GATE patterns
Connections
Builds on
Across subjects
No cross-subject links yet.
These algorithms are instances of divide and conquer whose recurrences are solved in solving recurrences. Counting inversions is merge sort with a counter (merge sort); the partition used by quickselect is that of quicksort. Kadane's linear scan for the maximum subarray is a dynamic programming idea, like the problems in dynamic programming on sequences.
PYQs
3 previous year questions from your book. I re-solved each one myself (2 by running or simulating, 1 by reasoning only); the book's key is shown next to my answer. All PYQs
Let P be an array containing n integers. Let t be the lowest upper bound on the number of comparisons of the array elements, required to find the minimum and maximum values in an arbitrary array of n elements. Which one of the following choices is correct?
- (a)t > 2n – 2
- (b)t > ⌈ log (n) ⌉ and t <= n
- (c)t > n and t <= 3 ⌈ n/2 ⌉
- (d)t > 3 ⌈ n/2 ⌉and t <= 2n – 2
Consider a sequence of 14 elements:A=[-5,-10,6,3,-1,-2,13,4,-9,-1,4,12,-3 ,0].The sequence sum S(i, j) = ∑j k=i A[k].Determine the maximum of S(i ,j), where 0≤ i≤ j< 14.(Divide and conquer approach may be used.)
The minimum number of comparisons required finding the minimum and the maximum of 100 numbers is ALGORITHMS Check Out Our Gate Courses & Secure Your Dream Rank ! HINTS & SOLUTIONS
Self-check
Question 1
What is the order of the time to multiply two -digit numbers by Karatsuba's method, and why?
Show answerHide
: three half-size products plus linear work give , and dominates .
Question 2
How many scalar multiplications does Strassen's method use for two matrices if it recurses down to ?
Show answerHide
(the classical method uses ).
Question 3
How many inversions cross the middle in (halves and )?
Show answerHide
All four pairs ( and each exceed and ): crossing inversions, and none inside the halves.
Question 4
Why does the median-of-medians recurrence give a linear bound?
Show answerHide
The two recursive calls are on at most and keys, and : the sizes shrink geometrically level by level, so the total work is a geometric series dominated by at the top.
Revision card
One-screen revision
- Fast power ; max subarray, inversions, closest pair: .
- Karatsuba ; Strassen .
- Closest pair: strip of width , sorted by , at most neighbours.
- Selection: quickselect expected linear, worst quadratic; median of medians (groups of ) linear worst case.
- Do not forget the crossing case.
References
- ·Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms (3rd edition), Chapter 4 (4.1 maximum subarray, 4.2 Strassen), Chapter 9 (medians and order statistics), Chapter 33 (33.4 closest pair), Problem 2-4 (inversions)
- ·Dasgupta, Papadimitriou, Vazirani, Algorithms, Chapter 2 (multiplication, matrix multiplication, medians)
- ·Kleinberg and Tardos, Algorithm Design, Chapter 5 (counting inversions, closest pair, integer multiplication)
Verification
Each algorithm was re-implemented in Python independently of the descriptions on this page and compared with a brute-force or standard answer: maximum subarray against brute force and Kadane (2000 random arrays), inversions against the quadratic count (2000 arrays), closest pair against brute force (600 random point sets, including many duplicates; the number of following strip points that need a distance test never exceeded 7), median of medians against sorting (1500 arrays), Karatsuba against Python integer multiplication with exactly 3^depth base products, and fast exponentiation against floor(log2 n) + popcount(n) - 1 multiplications for every n up to 3000. Strassen: the seven products and four output formulas were verified symbolically (sympy) and by a full recursion on random matrices, which also gave 7^k products and 6(7^k - 4^k) additions; the C measurements of the tables agree. The recurrence table was decided by the Master theorem procedure and numerics. Textbook chapter references are from memory. SECOND PASS (2026-11-02, done by the assistant, not a human check): every Self-check question was solved before the printed answer was read and all agreed; the definitions, worked examples, cheat box and traps were read claim by claim and the numbers re-derived by hand or by a small script (loop counts, recurrences, merge and quicksort counts and averages, hash probes and load-factor formulas, DP tables, MST and shortest-path runs, Floyd matrices); long C programs were not re-read line by line (they are compiled and compared by npm run verify:c, and their printed outputs were checked against the prose); tables and animations are machine output and were read, not re-run; No other defect found. Status raised to self-checked; verified needs a textbook or human check.
last verified: never
My notes (saved in this browser)