2Brute2Best
🔥0
01

Classic / boundaries (Binary Search Sub-pattern)

A sorted array: find a value, or the first / last position where a condition flips from false to true.

Signals in the problem statement
  • ›

    "sorted array" + "find target"

  • ›

    "insert position", "first and last position"

  • ›

    "must run in O(log n)"

  • ›

    integer square root

What makes it different

Equality search can stop early on a match. Boundary search never stops early — it keeps halving until lo == hi, and that position is the answer even when the target isn't there.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Binary Search
    Basic Anchor·LeetCode #704
    Easy
  2. 2
    Search Insert Position
    Basic Reinforcement·LeetCode #35
    Easy
  3. 3
    Sqrt(x)
    Slight Variation·LeetCode #69
    Easy
  4. 4Medium

Template

boundary-template.cpp
// First index i where ok(i) is true, for answers shaped false...false true...true.
// Returns n if no index works. Example ok: nums[i] >= target (= lower bound / insert position).
int firstTrue(vector<int>& nums, int target) {
    auto ok = [&](int i) { return nums[i] >= target; };
    int lo = 0, hi = (int)nums.size();     // hi = n means "none of them"
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (ok(mid)) hi = mid;             // mid works: the first true is mid or to its left
        else lo = mid + 1;                 // mid fails: the first true is right of mid
    }
    return lo;                             // lo == hi: the boundary
}
Remember this · Binary Search
Trigger
Sorted data, "minimum X such that…", "maximum X such that…", rotated arrays, answers that are monotonic (if X works, X+1 also works).
Think
Is there a yes/no question whose answers look like NNNNYYYY? Then binary search for the first Y.
Key question
What is my check function, and is it monotonic?