Sqrt(x) – Solution & Complexity
Solution Walkthrough
Step 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.
- We want the largest
Step 2: Handle the Small Cases
- For
x < 2, the integer square root equalsxitself (0 -> 0,1 -> 1). - Returning early avoids an empty search range.
- For
Step 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.
- Search the range
Step 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.
- The search halves the range each step, so time is