Coding Interview PatternsSqrt(x)
EasyModified Binary Search
Sqrt(x)
Explanation & Solution
Description
Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.
You must not use any built-in exponent function or operator (e.g., Math.sqrt or **).
Input: x = 4
Output: 2
Explanation: The square root of 4 is 2.
Constraints
0 <= x <= 2^31 - 1
Approach
Modified Binary Search pattern
1. Handle Base Cases
- If
x < 2, returnxdirectly (sqrt(0) = 0, sqrt(1) = 1).
2. Binary Search on [1, x]
- Set
lo = 1,hi = x, and trackans. - Compute
midand check ifmid <= x / mid(using division instead ofmid * midto avoid overflow).
3. Update Answer
- If
mid <= x / mid, thenmidcould be the answer → save it, search higher:lo = mid + 1. - Otherwise,
midis too large:hi = mid - 1.
4. Return
ansholds the largest integer whose square is ≤ x.
🧠 Key Insight
- Using
mid <= x / midinstead ofmid * mid <= xprevents integer overflow for large values of x.
Time
O(log x)binary search over [1, x].Space
O(1).