Lesson 13 · Core algorithms

Binary Search Variations

Every variation keeps the same loop: look at the middle, discard half. What changes is the question asked at the middle, and so the rule that decides which half survives.

Binary Search Variations concept diagramFour cards. First occurrence: in 1, 3, 5, 5, 5, 5, 8, 9 the middle holds 5, so index 3 is saved and the left part is kept. Rotated search: in 12, 15, 18, 22, 3, 7, 9 the left half 12 to 22 is sorted and does not contain 9, so the right part is kept. Rotated minimum: in 18, 22, 3, 7, 9, 12, 15 the middle 7 is less than the last value 15, so mid and the left are kept. Peak: in 2, 4, 7, 6, 3, 5, 1 the middle 6 is above its right neighbour, so mid and the left are kept.first occurrence of 5mid13555589keepa[mid] = 5: save 3, keep the leftmatch → hi = mid − 1rotated search for 9mid12151822379sorted halfkeep12..22 is sorted and lacks 9keep the other halfrotated minimummid18223791215keepa[mid] = 7 < a[hi] = 15: rising runhi = midpeak (unsorted)mid2476351keepa[mid] = 6 > a[mid + 1] = 3: downhillhi = mid
1

One Loop, Many Rules

Plain binary search asks one question at the middle: is this the target, or is the target left or right of it? A modified binary search keeps the loop and swaps the question. As long as the answer tells you which half cannot hold what you want, half the range goes each round and the cost stays O(log n).

So the work in each variation is finding the right question. The rest of this lesson walks through four of them, all on small arrays you can check by hand.

What each variation asks at mid
VariationQuestion at midKeep
First occurrencea[mid] == target?record it, go left
Last occurrencea[mid] == target?record it, go right
Rotated searchis a[lo..mid] sorted, and is the target in it?that half, or the other
Rotated minimuma[mid] > a[hi]?right of mid, else mid and left
Peaka[mid] < a[mid + 1]?right of mid, else mid and left
  • The keep rule must never discard the answer
  • The range must shrink every round, or the loop never ends
2

First and Last Occurrence

On 1, 3, 5, 5, 5, 5, 8, 9 a plain search for 5 stops at index 3, the first copy it happens to hit. To find the first and last occurrence, do not stop on a match. Record the index, then keep searching left for an earlier copy (or right for a later one). The loop ends when the range is empty, and the last recorded index is the answer.

The first copy of 5 is at 2 and the last at 5. Subtracting gives a way to count occurrences in sorted array data in O(log n) without scanning: 5 − 2 + 1 = 4 copies. If the target is absent, nothing is ever recorded and both searches return -1.

3

Searching a Rotated Sorted Array

Take a sorted array and move a block from the front to the back: 12, 15, 18, 22, 3, 7, 9. It is no longer sorted, so the plain rule breaks. Searching for 9, the middle value is 22, which is larger, so plain binary search goes left and misses.

One fact rescues it: cut a rotated array anywhere, and at least one side of the cut is sorted. If a[lo] ≤ a[mid], the left half is sorted; otherwise the right half is. On a sorted half you can tell for sure whether the target lies inside by checking its two ends. If it does, keep that half; if not, keep the other. For 9, the left half 12..22 is sorted and does not hold 9, so the search moves right, and finds 9 at index 6 on the third probe.

  • a[lo] ≤ a[mid]: left half sorted; else right half sorted
  • Target between the sorted half's ends: keep it; otherwise keep the other half
  • Practice: Search in Rotated Sorted Array
Key reference

Terms, operations, and practical uses

Key terms

  • Keep ruleThe test at mid that decides which half survives.
  • Rotation pointThe index right after the drop; it holds the minimum.
  • PeakA value larger than its neighbours.
Implementation

Code in Python, C++ and Java

def first_occurrence(a, target):
    lo, hi, found = 0, len(a) - 1, -1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            found = mid
            hi = mid - 1
        elif a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return found


def last_occurrence(a, target):
    lo, hi, found = 0, len(a) - 1, -1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            found = mid
            lo = mid + 1
        elif a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return found


def search_rotated(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[lo] <= a[mid]:
            if a[lo] <= target < a[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:
            if a[mid] < target <= a[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1


def min_rotated(a):
    lo, hi = 0, len(a) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] > a[hi]:
            lo = mid + 1
        else:
            hi = mid
    return lo


def peak(a):
    lo, hi = 0, len(a) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < a[mid + 1]:
            lo = mid + 1
        else:
            hi = mid
    return lo


a = [1, 3, 5, 5, 5, 5, 8, 9]
f, l = first_occurrence(a, 5), last_occurrence(a, 5)
print("first", f, "last", l, "count", l - f + 1)
print("first of 4:", first_occurrence(a, 4))
r = [12, 15, 18, 22, 3, 7, 9]
print("index of 9:", search_rotated(r, 9), "index of 10:", search_rotated(r, 10))
m = min_rotated(r)
print("minimum", r[m], "at", m)
print("peak index:", peak([2, 4, 7, 6, 3, 5, 1]))
#include <iostream>
#include <vector>
using namespace std;

int firstOccurrence(const vector<int>& a, int target) {
    int lo = 0, hi = (int)a.size() - 1, found = -1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == target) {
            found = mid;
            hi = mid - 1;
        } else if (a[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return found;
}

int lastOccurrence(const vector<int>& a, int target) {
    int lo = 0, hi = (int)a.size() - 1, found = -1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == target) {
            found = mid;
            lo = mid + 1;
        } else if (a[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return found;
}

int searchRotated(const vector<int>& a, int target) {
    int lo = 0, hi = (int)a.size() - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == target) return mid;
        if (a[lo] <= a[mid]) {
            if (a[lo] <= target && target < a[mid]) hi = mid - 1;
            else lo = mid + 1;
        } else {
            if (a[mid] < target && target <= a[hi]) lo = mid + 1;
            else hi = mid - 1;
        }
    }
    return -1;
}

int minRotated(const vector<int>& a) {
    int lo = 0, hi = (int)a.size() - 1;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] > a[hi]) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}

int peak(const vector<int>& a) {
    int lo = 0, hi = (int)a.size() - 1;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] < a[mid + 1]) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}

int main() {
    vector<int> a = {1, 3, 5, 5, 5, 5, 8, 9};
    int f = firstOccurrence(a, 5), l = lastOccurrence(a, 5);
    cout << "first " << f << " last " << l << " count " << l - f + 1 << "\n";
    cout << "first of 4: " << firstOccurrence(a, 4) << "\n";
    vector<int> r = {12, 15, 18, 22, 3, 7, 9};
    cout << "index of 9: " << searchRotated(r, 9) << " index of 10: " << searchRotated(r, 10) << "\n";
    int m = minRotated(r);
    cout << "minimum " << r[m] << " at " << m << "\n";
    cout << "peak index: " << peak({2, 4, 7, 6, 3, 5, 1}) << "\n";
}
public class Main {
    static int firstOccurrence(int[] a, int target) {
        int lo = 0, hi = a.length - 1, found = -1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] == target) {
                found = mid;
                hi = mid - 1;
            } else if (a[mid] < target) lo = mid + 1;
            else hi = mid - 1;
        }
        return found;
    }

    static int lastOccurrence(int[] a, int target) {
        int lo = 0, hi = a.length - 1, found = -1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] == target) {
                found = mid;
                lo = mid + 1;
            } else if (a[mid] < target) lo = mid + 1;
            else hi = mid - 1;
        }
        return found;
    }

    static int searchRotated(int[] a, int target) {
        int lo = 0, hi = a.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] == target) return mid;
            if (a[lo] <= a[mid]) {
                if (a[lo] <= target && target < a[mid]) hi = mid - 1;
                else lo = mid + 1;
            } else {
                if (a[mid] < target && target <= a[hi]) lo = mid + 1;
                else hi = mid - 1;
            }
        }
        return -1;
    }

    static int minRotated(int[] a) {
        int lo = 0, hi = a.length - 1;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] > a[hi]) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }

    static int peak(int[] a) {
        int lo = 0, hi = a.length - 1;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] < a[mid + 1]) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }

    public static void main(String[] args) {
        int[] a = {1, 3, 5, 5, 5, 5, 8, 9};
        int f = firstOccurrence(a, 5), l = lastOccurrence(a, 5);
        System.out.println("first " + f + " last " + l + " count " + (l - f + 1));
        System.out.println("first of 4: " + firstOccurrence(a, 4));
        int[] r = {12, 15, 18, 22, 3, 7, 9};
        System.out.println("index of 9: " + searchRotated(r, 9) + " index of 10: " + searchRotated(r, 10));
        int m = minRotated(r);
        System.out.println("minimum " + r[m] + " at " + m);
        System.out.println("peak index: " + peak(new int[] {2, 4, 7, 6, 3, 5, 1}));
    }
}
Watch it run

Step through it

Running on [1, 3, 5, 5, 5, 5, 8, 9] target 5 · rotated [12, 15, 18, 22, 3, 7, 9] target 9

target 5 · find the first and last occurrence1031525354558697lohilo = 0, hi = 7same halving, different rule on a match
Step 1

Find every 5, not just one

The array is sorted and 5 appears four times, at indexes 2 to 5. Plain binary search returns whichever copy it lands on first. To get the first copy and the last copy, the loop has to keep going after a match.

Output
1 / 14
4

Minimum of a Rotated Array

The smallest value sits right after the drop, and its index is how many places the array was rotated. Compare a[mid] with the last value a[hi]. If a[mid] is larger, the drop is to the right of mid, so lo = mid + 1. Otherwise mid and everything right of it is one rising run, so the minimum is mid or to its left: hi = mid.

On 12, 15, 18, 22, 3, 7, 9 that reads 22 > 9, then 7 < 9, then 3 < 7, and stops at index 4 with value 3. Comparing with the right end rather than the left matters: a sorted, unrotated array has its minimum at the left, and the right-end rule handles that without a special case.

5

Peaks and Other Unsorted Cases

Binary search can even work on unsorted data if the question has a direction. A peak is a value larger than both neighbours. If a[mid] < a[mid + 1], the values rise to the right, and climbing that way must reach a peak before the edge, so keep the right side. Otherwise keep mid and the left side. On 2, 4, 7, 6, 3, 5, 1 it returns index 2, the 7.

There may be other peaks (5 is one), and this finds just one of them. That is enough for Find Peak Element, and the same comparison drives Single Element in a Sorted Array, where the side of mid that breaks the pairing holds the answer.

  • Rising at mid: a peak exists to the right
  • Returns some peak, not the highest one
6

Duplicates and Other Traps

Repeated values can hide the rotation. In 3, 3, 1, 3 the left end, the middle and the right end are all 3, and no comparison says which side the 1 is on. The safe move is to drop one end and try again, which makes the worst case O(n) instead of O(log n). Search in Rotated Sorted Array II is that version.

Two other bugs recur across the family. Using lo < hi with hi = mid − 1 skips the last candidate; using lo ≤ hi with hi = mid loops forever. Pick one pair and keep it. For the base search and its lower and upper bound, see binary search; for searching a range of possible answers, see binary search on answer.

  • Equal ends in a rotated array: shrink by one, worst case O(n)
  • lo ≤ hi pairs with hi = mid − 1; lo < hi pairs with hi = mid