Builds onArrays and strings
01The idea
Binary search finds a position in a sorted list by halving the search range again and again. Look at the middle item. Because the list is sorted, that one comparison shows which half cannot hold the answer. Discard that half and repeat.
A list of a million items needs about 20 comparisons, because 2²⁰ is about a million. That is O(log n), against O(n) for checking items one by one.
The safest way to write it is to search for a boundary. A boundary is the first index where some condition becomes true. In a sorted list, a condition such as "the value is bigger than x" is false for a block at the start and true for the rest. You look for the first true.
Keep the range as lo to hi, where hi is not checked yet and may be the answer itself. Then each step is:
- Take
mid = (lo + hi) // 2. - If the condition is false at mid, the boundary is after mid. Set
lo = mid + 1. - If it is true at mid, the boundary is mid or before it. Set
hi = mid.
Stop when lo equals hi. That index is the boundary. If the condition is never true, the answer is len(nums).
02How to spot it
Binary search fits when:
- the input is sorted, and you need a position, a count or the first item that passes a test
- the problem asks for O(log n) time
- a yes or no condition flips once as you move through the input, so the answers are all no and then all yes
Many questions reduce to one boundary. "Where does x first appear?" is the first index with a value of at least x. "How many values are at most x?" is the first index with a value bigger than x. "Insert x and keep the list sorted" is the same first index.
The flip can also be over answers instead of indices. If you can test "is 50 enough?" and every bigger number is also enough, you can binary search the answer itself. That idea has its own lesson.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue