Sqrt(x)

Easy

Topics
MathBinary Search

Given a non-negative integer n, return the integer square root of n (the floor of the true square root). Do not use built-in sqrt.

Example 1

2²4
3²9
the largest square not exceeding 4
√4 is truncated to an integer, not rounded: the answer is the largest whole number whose square is still at most 4. 2² = 4 fits and 3² = 9 does not, so the answer is 2.
The two squares either side of the answer.
Input:  n = 4
Output: 2

Example 2

2²4
3²9
the largest square not exceeding 8
Input:  n = 8
Output: 2
Explanation: floor(2.828...) = 2.

Constraints

  • 0 <= n <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

The integer square root is the largest m with m² ≤ n. Since m² grows monotonically, binary-search for that boundary instead of scanning.

Approach

  1. Binary-search m in [0, n].
  2. If m² ≤ n, record m and search higher.
  3. Otherwise search lower.
  4. Return the last valid m.

Walkthrough

n = 8
lo=0 hi=8 mid=4 16>8 -> hi=3
lo=0 hi=3 mid=1 1<=8 ans=1 lo=2
lo=2 hi=3 mid=2 4<=8 ans=2 lo=3
lo=3 hi=3 mid=3 9>8 hi=2 -> answer 2

Complexity

  • Time — O(log n): binary search halves the range each step.
  • Space — O(1): a few integers.

Common Pitfalls

  • mid * mid can overflow 32-bit ints for large n — use 64-bit or compare mid against n / mid.
  • The midpoint itself is the other overflow to watch: prefer lo + (hi - lo) / 2 over (lo + hi) / 2, which can wrap negative in Java and C++ once lo + hi exceeds 2^31 - 1.

Full Solution — all languages

class Solution:
    def mySqrt(self, n):
        if n < 2:
            return n
        lo, hi = 1, n // 2
        while lo <= hi:
            mid = (lo + hi) // 2
            if mid * mid <= n:
                lo = mid + 1
            else:
                hi = mid - 1
        return hi
Asked at Citadel Zoho
SensAI
Beta
Tap the mic to stop voice mode