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.
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.
| Variation | Question at mid | Keep |
|---|---|---|
| First occurrence | a[mid] == target? | record it, go left |
| Last occurrence | a[mid] == target? | record it, go right |
| Rotated search | is a[lo..mid] sorted, and is the target in it? | that half, or the other |
| Rotated minimum | a[mid] > a[hi]? | right of mid, else mid and left |
| Peak | a[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
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.
- Match: save mid, then hi = mid − 1 (first) or lo = mid + 1 (last)
- Count = last − first + 1, two searches of O(log n) each
- Practice: Find First and Last Position of Element in Sorted Array
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
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.
Related
- Binary searchThe base loop, with lower and upper bound.
- Binary search on answerHalving a range of candidate answers.
- Search in Rotated Sorted ArrayThe rotated keep rule as a problem.
- Find Peak ElementWalk uphill in O(log n).
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}));
}
}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
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.
- a[mid] > a[hi]: lo = mid + 1; else hi = mid
- Loop while lo < hi; the answer is lo
- Practice: Find Minimum in Rotated Sorted Array
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
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