easyMathBinary Search

Sqrt(x)

easyTime: O(log x)Space: O(1)

Recognize the pattern

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

Brute force idea

The naive version of Sqrt(x) sounds like this: 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.

Better approach

The deeper shift in Sqrt(x) is this: 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.

Key invariant

At the center of Sqrt(x) is one steady idea: 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.

Watch out for

A common way to get lost in Sqrt(x) is this: 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