Sqrt(x)

Easy Binary Search Search on Answer Range Original on LeetCode

Sqrt(x) is a easy binary search problem solved with the search on answer range pattern. The best approach, optimal (binary search for the last true), runs in O(log x) time and O(1) space. Below are 2 approaches in Java, from linear search up.

Problem

Given a non-negative integer x, return its square root rounded down to an integer, without using a built-in power or square root function.

Examples

Example 1

Input
x = 16
Output
4

Example 2

Input
x = 20
Output
4
Why
sqrt(20) ≈ 4.47, rounded down.

Constraints

  • 0 <= x <= 2^31 - 1
  • No built-in pow or sqrt.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.

ApproachTimeSpace
Linear searchO(√x)O(1)
Optimal (binary search for the last true)O(log x)O(1)

2Optimal (binary search for the last true)

TimeO(log x)
SpaceO(1)

r · r <= x is true for small r and false for large r. Binary search for the last r where it is true, using long for the square.

  1. lo = 0, hi = x.
  2. If mid * mid <= x: ans = mid, lo = mid + 1. Else hi = mid - 1.
Java
class Solution {
    public int mySqrt(int x) {
        long lo = 0, hi = x, ans = 0;
        while (lo <= hi) {
            long mid = (lo + hi) / 2;
            if (mid * mid <= x) { ans = mid; lo = mid + 1; }
            else hi = mid - 1;
        }
        return (int) ans;
    }
}

Edge cases to test

  • x = 0 and x = 1
  • mid * mid overflows int; use long

Hints

Hint 1

Find the largest r with r · r <= x.

FAQ

What is the best time complexity for Sqrt(x)?

Optimal (binary search for the last true) runs in O(log x) time and O(1) extra space.

Which pattern does Sqrt(x) use?

It is a binary search problem that uses the search on answer range pattern. Other problems with the same pattern: Pow(x, n) (Binary Exponentiation), Find Nth root of M, Find position of an element in a sorted array of infinite numbers (Galloping Search).

Is there a brute force solution for Sqrt(x)?

Yes. Linear search takes O(√x) time and O(1) space. Increase r while (r + 1)^2 <= x.

Which edge cases should I test for Sqrt(x)?

x = 0 and x = 1; mid mid overflows int; use long.