NeetCode 150, stage 5: Binary Search

← Stack · All 150 problems · Linked List →

Binary search cuts the range of candidates in half at each step, so it needs O(log n) steps. This stage trains two loop shapes and the rule of each one: what the range means, and how each step makes it smaller. The same loop also searches a range of possible answers, not only the indexes of a slice.

Garden notes: the Go syntax for this stage, Binary Search, Sorting.

Problems on this page

#ProblemLevelPatternTemplate
1704. Binary SearchEasyBinary search, exact valueA: Exact value
274. Search a 2D MatrixMediumBinary search, exact valueA: Exact value
3875. Koko Eating BananasMediumBinary search on the answerB: First true
4153. Find Minimum in Rotated Sorted ArrayMediumFirst true on a rotated sliceB: First true
533. Search in Rotated Sorted ArrayMediumBinary search on a rotated sliceC: Rotated sorted slice
6981. Time Based Key-Value StoreMediumMap of sorted slices, first trueB: First true
74. Median of Two Sorted ArraysHardBinary search on a partitionD: Partition of two sorted slices

Templates to memorize

Template A: Exact value

Signal

The slice is sorted, and the problem looks for one value. The result is an index, or “not there”.

// TEMPLATE A: exact value. The range lo..hi is inclusive at the two ends.
func indexOf(nums []int, target int) int {
    lo, hi := 0, len(nums)-1
    for lo <= hi { // the range still has one item or more
        mid := lo + (hi-lo)/2 // 1. MIDDLE
        switch {              // 2. COMPARE
        case nums[mid] == target:
            return mid
        case nums[mid] < target:
            lo = mid + 1 // 3. DROP HALF: mid and all the items on its left
        default:
            hi = mid - 1 // mid and all the items on its right
        }
    }
    return -1 // the range is empty: the target is not there
}

The moves are MIDDLE, COMPARE, then DROP HALF. The two ends lo and hi are inclusive, so the loop condition is lo <= hi. Each move skips mid, with mid + 1 or mid - 1, because the comparison already tested it. A move to mid itself can loop forever.

Say it

“The slice is sorted, so one comparison with the middle drops half of the range. That gives O(log n) time and O(1) space.”

Template B: First true

Signal

A test is false for the small candidates and true for the large ones, and the problem wants the boundary. Typical words are “minimum speed”, “smallest capacity”, “first item larger than X”. When the candidates are values and not indexes, this is a search on the answer.

// TEMPLATE B: first true. ok is false, false, ..., true, true on lo..hi.
// It returns the smallest x for which ok(x) is true. ok(hi) must be true.
func firstTrue(lo, hi int, ok func(int) bool) int {
    for lo < hi { // the range still has two candidates or more
        mid := lo + (hi-lo)/2 // 1. MIDDLE: it is always less than hi
        if ok(mid) {          // 2. TEST
            hi = mid // 3. KEEP mid: it can be the answer
        } else {
            lo = mid + 1 // DROP mid and all the candidates on its left
        }
    }
    return lo // lo == hi: one candidate stays, and it is the answer
}

The moves are MIDDLE, TEST, then KEEP or DROP. A true mid can be the answer, so keep it with hi = mid. A false mid cannot, so drop it with lo = mid + 1. The loop condition is lo < hi, and the loop ends with one candidate. Choose hi so that the test is true there. In Go, sort.Search(n, f) is this template for the indexes 0 to n-1.

Say it

“If a speed works, each faster speed works too, so the candidates are false, then true, and I binary search for the first true. Each test costs O(n), so the total is O(n log m).”

Template C: Rotated sorted slice

Signal

The input is a sorted slice after a rotation, with different values, and the problem wants O(log n). The slice has two sorted parts.

// TEMPLATE C: rotated sorted slice. One half of lo..hi is always sorted.
func indexInRotated(nums []int, target int) int {
    lo, hi := 0, len(nums)-1
    for lo <= hi {
        mid := lo + (hi-lo)/2 // 1. MIDDLE
        if nums[mid] == target {
            return mid
        }
        // 2. FIND THE SORTED HALF: here it is lo..mid
        if nums[lo] <= nums[mid] {
            // 3. TEST ITS RANGE
            if nums[lo] <= target && target < nums[mid] {
                // 4. DROP HALF: the target is in the sorted half
                hi = mid - 1
            } else {
                // the target is not there, so go to the other half
                lo = mid + 1
            }
        } else { // the sorted half is mid..hi
            if nums[mid] < target && target <= nums[hi] {
                lo = mid + 1
            } else {
                hi = mid - 1
            }
        }
    }
    return -1
}

The moves are MIDDLE, FIND THE SORTED HALF, TEST ITS RANGE, then DROP HALF. One half of the range is always sorted, and only a sorted half has a range that you can test. Write nums[lo] <= nums[mid] with <=, because lo equals mid when two items stay. The loop itself is Template A.

Say it

“After a rotation, one half around the middle is still sorted. I check if the target is inside the range of that half, and if it is not, I search the other half, so it is still O(log n).”

Template D: Partition of two sorted slices

Signal

The input is two sorted slices, and the problem wants the median or the k-th item in logarithmic time. A merge costs O(m + n), which is too slow.

// TEMPLATE D: partition of two sorted slices. a must be the shorter slice.
// It returns i and j: the left half of the merged slice is a[:i] plus
// b[:j].
func splitTwoSorted(a, b []int) (int, int) {
    half := (len(a) + len(b) + 1) / 2 // the size of the left half
    lo, hi := 0, len(a)               // i can be 0, 1, ..., len(a)
    for lo <= hi {
        i := lo + (hi-lo)/2 // 1. CUT a after i items
        j := half - i       // 2. DERIVE the cut in b
        switch {            // 3. CHECK the two borders
        case i > 0 && j < len(b) && a[i-1] > b[j]:
            hi = i - 1 // 4. MOVE: a gives too many items to the left half
        case j > 0 && i < len(a) && b[j-1] > a[i]:
            lo = i + 1 // a gives too few items
        default:
            return i, j // each left item <= each right item
        }
    }
    return 0, half // not reached when a and b are sorted
}

The moves are CUT, DERIVE, CHECK, then MOVE. Search the cut in the shorter slice, so the cut in the other slice never becomes negative. A cut at index 0 or at the end has no item on one side. Test the index before you read the item.

Say it

“I do not merge: I binary search a cut in the shorter array, and the cut in the other array follows from the half size. The cut is right when the left borders are not larger than the right borders, which takes O(log of the shorter length).”

Mistakes in this stage

  • A mix of the two shapes loops forever: lo <= hi goes with mid ± 1, and lo < hi goes with hi = mid.
  • (lo + hi) / 2 can overflow a 32-bit integer. Write lo + (hi-lo)/2 as a habit.
  • sort.Search returns n when no index passes the test. Check the result before you use it as an index.
  • In a search on the answer, lo and hi are values, not indexes. A speed of 0 causes a division by zero, so start at 1.

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

LeetCode 704 · Easy

74. Search a 2D Matrix

LeetCode 74 · Medium

875. Koko Eating Bananas

LeetCode 875 · Medium

153. Find Minimum in Rotated Sorted Array

LeetCode 153 · Medium

33. Search in Rotated Sorted Array

LeetCode 33 · Medium

981. Time Based Key-Value Store

LeetCode 981 · Medium

4. Median of Two Sorted Arrays

LeetCode 4 · Hard


← Stack · All 150 problems · Linked List →