AAlgoLoopSpaced repetition for LeetCode
EASYBinary SearchLeetCode ↗

Sqrt(x)

The key idea

The answer r is the largest integer whose square does not exceed x. Since r*r grows monotonically with r, you can binary-search the range [0, x] for that boundary instead of scanning every candidate.

Problem

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 such as pow(x, 0.5) in C++ or x ** 0.5 in Python.

Constraints

Examples

Input: x = 4 Output: 2
Input: x = 8 Output: 2

Complexity

Time: O(log n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Binary Search problems