Binary Search · Pattern 6 of 8
Binary search over numbers: roots, powers, unbounded ranges
The search space is a range of numbers, not an array. Square roots and nth roots: the largest x with x² ≤ n. Plus two cousins: halving the exponent and galloping into an unbounded array.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Find an integer root without a math library
- Compute a power quickly, or with a huge exponent
- The array has no known length (an infinite or streamed input)
The template
// largest x with x * x <= n
int mySqrt(int n) {
long lo = 0, hi = n;
while (lo < hi) {
long mid = lo + (hi - lo + 1) / 2; // round up because we set lo = mid
if (mid * mid <= n) lo = mid; // mid works: the answer is mid or bigger
else hi = mid - 1;
}
return (int) lo;
} def my_sqrt(n): # largest x with x * x <= n
lo, hi = 0, n
while lo < hi:
mid = (lo + hi + 1) // 2 # round up because we set lo = mid
if mid * mid <= n:
lo = mid # mid works: the answer is mid or bigger
else:
hi = mid - 1
return lo // largest x with x * x <= n
int mySqrt(int n) {
long long lo = 0, hi = n;
while (lo < hi) {
long long mid = lo + (hi - lo + 1) / 2; // round up because we set lo = mid
if (mid * mid <= n) lo = mid; // mid works: the answer is mid or bigger
else hi = mid - 1;
}
return (int)lo;
} // largest x with x * x <= n
function mySqrt(n) {
let lo = 0, hi = n;
while (lo < hi) {
const mid = Math.floor((lo + hi + 1) / 2); // round up because we set lo = mid
if (mid * mid <= n) lo = mid; // mid works: the answer is mid or bigger
else hi = mid - 1;
}
return lo;
} The variations
-
1Integer roots
The condition "x² ≤ n" (or "xⁿ ≤ m") is true, true, … false: binary search the last true. Search over
[0, n], not over an array.Now you solve -
2Halve the exponent
The same halving idea, applied to the exponent: xⁿ = (x²)^(n/2), times x when n is odd. log n multiplications instead of n. Careful with negative n.
-
3Gallop, then search
No end in sight? Double
hi(1, 2, 4, 8, …) untila[hi] >= target, then binary search between the last two bounds. Still O(log p) where p is the position.
Mistakes to avoid
mid * midoverflowing an int: use long (Java), long long (C++).- Rounding
middown while settinglo = mid: with lo = 2, hi = 3 it loops forever. - For nth roots, stop multiplying as soon as the product passes m, or it overflows.
Lesson done
Next: Binary search on the answer →Mark it done once you can write the template from memory and you have solved the worked examples yourself.