Problem Statement

Sqrt(x)

You are given a non-negative whole number x. Return its square root, but rounded down to the nearest whole number. The square root of a number is the value that, when multiplied by itself, gives you that number. For example, the square root of 9 is 3 because 3 times 3 is 9. The answer must be a whole number that is zero or larger, and you are not allowed to use any built-in power or square-root function. You have to figure it out yourself.

easyMathBinary SearchTime: O(log x) · Space: O(1)

Signals to notice

find integer square rootsearch in sorted range 1.xprecision not needed

Brute force first

Try every integer from 1 upward until i² > x. Linear search through candidates. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Binary search on the range [1, x]: if mid² ≤ x, the answer is mid or higher; if mid² > x, it's lower. Converges in steps. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Trace it on x=8

x=8 >= 2, so init: left=1, right=x//2=4
mid=(1+4)//2=2, 2*2=4 < 8 -> too small, left=mid+1=3 (now left=3, right=4)
mid=(3+4)//2=3, 3*3=9 > 8 -> too big, right=mid-1=2 (now left=3, right=2)
left=3 > right=2 -> loop ends
return right=2  (largest m with m*m<=8, since 2*2=4<=8<9=3*3)

What must stay true

The answer is the largest integer m where m² ≤ x. Binary search narrows the range by half each step, and the left boundary always stays ≤ the answer. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Shape of the loop

if x < 2: return x
left, right = 1, x // 2
while left <= right:
    mid = (left + right) // 2
    if mid*mid == x: return mid
    elif mid*mid < x: left = mid + 1   # too small, go right
    else: right = mid - 1              # too big, go left
return right                           # largest m with m*m <= x

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Integer overflow when computing mid * mid — use long/BigInt or compare mid vs x/mid instead of mid*mid vs x. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Binary Search Pattern