InterviewSam
Tech TracksStudySystem DesignAptitudeDaily Quiz
Log inStart free
Tech TracksStudySystem DesignAptitudeDaily Quiz
All topics

Binary Search

Halve the search space each step, on arrays and on answers.

5 pages, free to read

Start studying
  1. 1

    Classic binary search

    Beginner

    In a sorted array, compare the target with the middle element and throw away the half that cannot contain it, so you find any value in O(log n) steps.

    8 min read
  2. 2

    Lower & upper bound

    Intermediate

    Lower bound finds the first index whose value is >= target and upper bound finds the first index whose value is > target, which gives first and last positions, counts and insert points in O(log n).

    9 min read
  3. 3

    Rotated sorted arrays

    Intermediate

    A rotated sorted array is two sorted runs glued together; at every mid point at least one half is still sorted, so you can check that half and keep binary searching in O(log n).

    9 min read
  4. 4

    Binary search on the answer

    Advanced

    When you can quickly check whether a candidate answer is good enough, and goodness only flips once as the candidate grows, binary search over the range of possible answers instead of over an array.

    11 min read
  5. 5

    Searching a sorted matrix

    Intermediate

    If the whole matrix reads as one sorted list row by row, binary search it as a flat array in O(log(m x n)); if only rows and columns are each sorted, walk a staircase from a corner in O(m + n).

    9 min read