Sqrt(x) – Solution & Complexity
1. Understand the Pattern
- We want the largest
rwithr * r <= x. - The answer is monotonic: if
r * r <= x, then every smaller value also qualifies. - Monotonicity is exactly what binary search exploits.
2. Handle the Small Cases
- For
x < 2, the integer square root equalsxitself (0 -> 0,1 -> 1). - Returning early avoids an empty search range.
3. Binary Search the Root
- Search the range
[1, x]for the largestmidwhose square is<= x. - Move the lower bound up when
mid * mid <= x, otherwise move the upper bound down. - Track the best valid
midas you go.
4. Final Solution and Complexity
- The search halves the range each step, so time is
O(log x). - Space is
O(1). - In fixed-width languages, compare
midtox // midto dodgemid * midoverflow.