CodePlus
Calendar

Introduction batch

Divide & Conquer Fundamentals

Sunday, 1 November 2026, 3:00 pm – 5:00 pm IST

5006 - CC3

CodePlus Senior Members Team

How to break a big problem into smaller copies of itself, solve the pieces and combine the answers. We build the idea through ten quick problems, from binary search to merge sort.

Class notes

Welcome back! The slides from today are above. Download them from the link at the top of this page.

Below is a C++ solution for every quick problem from class. Try each one yourself first, then compare. Every solution follows the same three moves: divide the problem, conquer the pieces, combine the answers.

All snippets assume #include <bits/stdc++.h> and using namespace std; at the top.

Part 1: Binary search

Binary search is divide and conquer where you keep only one half, so the combine step is empty. Each problem below asks the same question in a new disguise: what is my yes/no question, and does it flip once?

Problem 1: Guess my number

A number is hidden between 1 and 1000. Answer: 10 guesses in the worst case, because every guess throws away half of what is left.

C++
// The secret is somewhere in [1, n]. Each guess says "too low", "too high" or "correct".
int guessNumber(int n, int secret) {
    int lo = 1, hi = n, guesses = 0;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        guesses++;
        if (mid == secret) return guesses;
        if (mid < secret) lo = mid + 1;   // too low: keep the upper half
        else hi = mid - 1;                // too high: keep the lower half
    }
    return guesses;
}

Problem 2: Find the name

A phone book has 1,000,000 sorted names. Answer: 20 looks. One look rules out half the book, but only because the book is sorted. A shuffled book could need all 1,000,000 looks.

C++
// names is sorted A to Z. Returns the index of target, or -1.
int findName(const vector<string>& names, const string& target) {
    int lo = 0, hi = (int)names.size() - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (names[mid] == target) return mid;
        if (names[mid] < target) lo = mid + 1;   // target comes later in the book
        else hi = mid - 1;                       // target comes earlier
    }
    return -1;
}

Problem 3: The first bad version

Versions 1 to 100, and from some version onward every version is bad. Answer: 7 tests. Here we are searching for a boundary, not a value.

C++
bool isBad(int version);   // given: false for good versions, true from the first bad one on

int firstBad(int n) {
    int lo = 1, hi = n;   // the answer is always inside [lo, hi]
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (isBad(mid)) hi = mid;       // mid might be the first bad one, so keep it
        else lo = mid + 1;              // everything up to mid is good
    }
    return lo;
}

There are two loop shapes to remember:

You wantLoopUpdate rules
A value that is presentwhile (lo <= hi)lo = mid + 1 or hi = mid - 1, return when equal
A boundary (first yes)while (lo < hi)hi = mid or lo = mid + 1

Problem 4: Count the ones

An array holds 0s followed by 1s. Count the 1s without looking at every entry. Answer: find where it flips from 0 to 1 (about 20 looks for 1,000,000 entries), then subtract. It is the same boundary search as the bad version: 0 is good, 1 is bad.

C++
// a looks like 0 0 0 1 1 1 1. Returns how many ones it has.
int countOnes(const vector<int>& a) {
    int lo = 0, hi = (int)a.size();   // hi = a.size() means "there is no 1 at all"
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == 1) hi = mid;      // the first 1 is at mid or to its left
        else lo = mid + 1;              // the first 1 is to the right
    }
    return (int)a.size() - lo;          // lo is the index of the first 1
}

Problem 5: Square root by guessing

Find the whole part of the square root of 2,000,000 using only multiplication. Answer: 1414, in about 21 guesses. There is no list to search. We search over the possible answers, because "is g * g <= x?" says yes, yes, yes, then no, no, no.

C++
// Largest g with g * g <= x. The yes/no question is: is g * g <= x ?
long long floorSqrt(long long x) {
    long long lo = 0, hi = x;
    while (lo < hi) {
        long long mid = lo + (hi - lo + 1) / 2;   // round up so the range always shrinks
        if (mid <= x / mid) lo = mid;             // same as mid * mid <= x, without overflow
        else hi = mid - 1;
    }
    return lo;
}

Part 2: Dividing in other ways

Problem 6: The heavy coin

Nine identical-looking coins, one heavier, and a balance scale. Answer: 2 weighings. The scale has three outcomes (left heavier, right heavier, balanced), so we divide by 3, not 2: 9 coins become 3, then 3 become 1.

C++
// w[i] is 1 for a normal coin and 2 for the heavy one. The scale only compares two sums.
// Returns the heavy coin's index among [lo, hi) and counts the weighings.
int findHeavy(const vector<int>& w, int lo, int hi, int& weighings) {
    while (hi - lo > 1) {
        int third = (hi - lo + 2) / 3;                 // group size, rounded up
        int aEnd = lo + third, bEnd = min(lo + 2 * third, hi);
        int left = 0, right = 0;
        for (int i = lo; i < aEnd; i++) left += w[i];      // group A
        for (int i = aEnd; i < bEnd; i++) right += w[i];   // group B
        weighings++;
        if (left > right) hi = aEnd;                       // heavy coin is in A
        else if (right > left) { lo = aEnd; hi = bEnd; }   // heavy coin is in B
        else lo = bEnd;                                    // balanced: it is in the group left out
    }
    return lo;
}

Problem 7: Power in a hurry

Compute 2^30 in fewer than 29 multiplications. Answer: 7. Halve the exponent, compute the half once, and square it. For n it takes about log n multiplications.

C++
long long power(long long x, long long n, long long mod) {
    if (n == 0) return 1 % mod;
    long long half = power(x, n / 2, mod);        // compute the half ONCE and reuse it
    long long result = half * half % mod;
    if (n % 2 == 1) result = result * (x % mod) % mod;   // odd exponent: one extra x
    return result;
}

The mod is there because powers get huge. For 10^9 + 7, the product of two numbers below mod still fits in a long long.

Part 3: Merge, and count while merging

Problem 8: Largest number, the long way

Find the largest of 8 numbers by splitting in half. Answer: the combine step is one comparison, so the total is 7 comparisons, the same as a plain loop. Divide and conquer is not automatically faster; it pays off when the combine step is clever.

C++
int largest(const vector<int>& a, int lo, int hi) {   // looks at a[lo, hi)
    if (hi - lo == 1) return a[lo];                    // base case: one number
    int mid = lo + (hi - lo) / 2;
    int left = largest(a, lo, mid);                    // conquer the left half
    int right = largest(a, mid, hi);                   // conquer the right half
    return max(left, right);                           // combine: one comparison
}

Problem 9: Merge two sorted lists

Merge [1 4 7] and [2 3 9]. Answer: two fingers, one pass. Compare the fronts, take the smaller, move that finger. That is 5 comparisons for 6 numbers, and at most n - 1 in general.

C++
vector<int> mergeSorted(const vector<int>& a, const vector<int>& b) {
    vector<int> result;
    size_t i = 0, j = 0;                               // the two fingers
    while (i < a.size() && j < b.size()) {
        if (a[i] <= b[j]) result.push_back(a[i++]);    // take the smaller front number
        else result.push_back(b[j++]);
    }
    while (i < a.size()) result.push_back(a[i++]);     // one list ran out: copy the rest
    while (j < b.size()) result.push_back(b[j++]);
    return result;
}

This merge is exactly the "combine" step of merge sort. Splitting is free, all the real work is merging:

C++
void mergeSort(vector<int>& a, int lo, int hi) {      // sorts a[lo, hi)
    if (hi - lo <= 1) return;                          // base case: already sorted
    int mid = lo + (hi - lo) / 2;
    mergeSort(a, lo, mid);                             // divide and conquer both halves
    mergeSort(a, mid, hi);
    inplace_merge(a.begin() + lo, a.begin() + mid, a.begin() + hi);   // combine: the merge from problem 9
}

There are about log n levels, and every level touches all n numbers, so merge sort takes O(n log n). For a million numbers that is about 2 x 10^7 steps instead of 10^12.

Problem 10: Count the disorder

An inversion is a pair where a bigger number comes before a smaller one. [2 4 1 3 5] has 3 inversions: (2,1), (4,1), (4,3). Checking every pair is O(n^2). Answer: count them while merging. When a number from the right half is taken, it jumps over everything still waiting on the left, and each of those is an inversion.

C++
// Sorts a[lo, hi) and returns the number of inversions inside it.
long long countInversions(vector<int>& a, int lo, int hi) {
    if (hi - lo <= 1) return 0;
    int mid = lo + (hi - lo) / 2;
    long long count = countInversions(a, lo, mid) + countInversions(a, mid, hi);

    vector<int> merged;
    int i = lo, j = mid;
    while (i < mid && j < hi) {
        if (a[i] <= a[j]) merged.push_back(a[i++]);
        else {
            count += mid - i;                  // a[j] jumps over everything still waiting on the left
            merged.push_back(a[j++]);
        }
    }
    while (i < mid) merged.push_back(a[i++]);
    while (j < hi) merged.push_back(a[j++]);
    copy(merged.begin(), merged.end(), a.begin() + lo);
    return count;
}

Cheat sheet

ProblemDivideCombineTotal
Binary searchhalve, keep one halfnothinglog n
Search the answerhalve the range of guessesone yes/no checklog range
Largest numbertwo halves1 comparisonn
Merge sorttwo halvesmerge: nn log n
Fast powerhalve the exponent1 multiplicationlog n
Heavy cointhree groupsnothinglog base 3 of n

Try these next

Say the divide step and the combine step in words before you write any code.

Read more: Binary search on cp-algorithms.

Stuck on anything? Ask any of us. See you in class!

Feedback

Tell us how the class went

How was this class?
How was the pace?

Only the CodePlus team can read this. It's never shown publicly.