Problem
Given a non-negative integer, find its integer square root โ the largest integer whose square does not exceed the input. No floating-point math is needed; you only return the whole-number part.
- Input:
x = 8 - Output:
2 - Explanation: โ8 โ 2.828, so we truncate to 2.
Counter-example: x = 9 โ 3 (exact square root, no truncation).
Intuition
You're searching for the largest integer r such that r * r โค x. That's a classic binary search target: values below the answer satisfy the condition, values above don't โ a monotone boundary. Instead of checking every integer from 0 to โx, you can halve the search space each step and find the answer in O(log x).
Approach 1 โ Linear Scan
Step from 0 upward, advancing as long as the next integer still fits. Stop when squaring the next candidate would exceed x.
- Start
answerat 0. - Check whether
(answer + 1)ยฒis still โค x. - If yes, increment
answer. - Repeat until the check fails, then return
answer.
1def mySqrt(x: int) -> int:
2 answer = 0
3 while (answer + 1) * (answer + 1) <= x:
4 answer += 1
5 return answerTime: O(โx) โ we iterate roughly โx times before the condition fails.
Space: O(1) โ only the running counter.
Approach 2 โ Binary Search
Search in the range [0, x] for the largest integer whose square is โค x. Each iteration eliminates half the remaining candidates.
- Initialize
left = 0,right = x. - Compute
mid = left + (right - left) / 2to avoid overflow. - If
mid * mid == x, returnmidimmediately. - If
mid * mid < x, the answer is at leastmidโ moveleft = mid + 1. - If
mid * mid > x, the answer is belowmidโ moveright = mid - 1. - When the loop ends (
left > right),rightis the largest value confirmed to satisfyr * r โค xโ return it.
1def mySqrt(x: int) -> int:
2 left, right = 0, x
3 while left <= right:
4 mid = left + (right - left) // 2
5 if mid * mid == x:
6 return mid
7 elif mid * mid < x:
8 left = mid + 1
9 else:
10 right = mid - 1
11 return right # right is the floor of sqrt(x) when loop exitsTime: O(log x) โ the search range halves each iteration.
Space: O(1) โ only a few pointers.
Complexity Summary
| Approach | Time | Space | When to use |
|---|---|---|---|
| Linear Scan | O(โx) | O(1) | Only for tiny inputs or when code simplicity is paramount |
| Binary Search | O(log x) | O(1) | General case โ standard for any "find the boundary" problem |
Common Mistakes
-
Integer overflow in
mid * mid: During early iterations,midcan be close toxitself (up to ~2 billion for max input). As anint,mid * midoverflows before the search narrows. Declaremidaslongin Java orlong longin C++; Python handles big integers natively. -
Returning
leftinstead ofrightafter the loop: When binary search exits withleft > right, it'srightthat holds the last index confirmed to satisfyr * r โค x. Returningleftyields a value one too high for every non-perfect-square input. -
Unsafe bounds when starting
right = x / 2: Settingright = x / 2is a valid optimization since โx โค x / 2 for x โฅ 4, but it breaks for x = 0 and x = 1 wherex / 2 = 0, making the answer 1 unreachable. Either startright = xor add an early return for x < 2. -
Overflow in the linear scan's condition: Writing
i * i <= xin Java/C++ overflows onceiexceeds ~46341 on a 32-bit int. Usei <= x / ito avoid squaring, or cast tolong/long longas shown above. -
Returning ceiling instead of floor: It's easy to flip the binary search direction and accidentally return the smallest integer whose square is โฅ x. The floor requires keeping
right = mid - 1when too high, and returningrightโ double-check the invariant against the examplex = 8 โ 2, not 3.
Related Problems
Binary Searchโ pure binary search template: the same left/right/mid structure used hereFind First And Last Position Of Element In Sorted Arrayโ binary search to locate a boundary, same "return right" patternPow(x, n)โ companion math problem; fast exponentiation uses the same "halve the problem" strategyKoko Eating Bananasโ binary search on the answer space, not an array; same monotone-condition patternCapacity To Ship Packages Within D Daysโ another binary-search-on-answer problem where the feasibility check is the key insight