Easy dsa binary-search

Sqrtx

The 30 second answer

I need the integer square root of a non-negative int, meaning the largest integer whose square is at most x. I binary-search the answer in 1 to x / 2, compare mid times mid against x using a long so the product cannot overflow, and keep the last mid that was small enough.

Could you say this in an interview?

Problem Given a non-negative integer x, return the integer part of its square root, that is the largest integer mid such that mid * mid <= x. You may not use a built-in exponent function. Original: LeetCode 69: Sqrt(x).

Understanding the prompt The official title is Sqrt(x). The answer is an integer, so 8 returns 2, not a real number. x = 0 and x = 1 are their own roots and should be handled before a range that uses x / 2. mid * mid does not fit in a 32-bit int for large mid, so the product must be computed in a long.

Pattern recognition Binary search on the answer: the predicate mid * mid <= x is true for a prefix of 0..x and false after that.

Brute force Increment i from 0 until i * i exceeds x: O(sqrt(x)).

Optimal If x is 0 or 1, return x. Otherwise search lo = 1, hi = x / 2. For each mid, compute (long) mid * mid. Equal returns mid. If the square is less than x, record mid as a candidate and search to the right; otherwise search to the left. Integer.MAX_VALUE is a useful overflow check: its integer square root is 46340, because 46340 squared fits in an int and 46341 squared does not.

Alternatives Newton's method also works and often converges faster, but binary search is easier to get right under interview pressure. Math.sqrt is forbidden by the problem statement.

Java solution

public class Sqrtx {
    static int mySqrt(int x) {
        if (x < 2) return x;
        int lo = 1, hi = x / 2, ans = 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            long sq = (long) mid * mid;
            if (sq == x) return mid;
            if (sq < x) {
                ans = mid;
                lo = mid + 1;
            } else hi = mid - 1;
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(mySqrt(4));          // 2
        System.out.println(mySqrt(8));          // 2
        System.out.println(mySqrt(0));          // 0
        System.out.println(mySqrt(1));          // 1
        System.out.println(mySqrt(Integer.MAX_VALUE)); // 46340
    }
}

Complexity O(log x) time, O(1) extra space.

Edge cases

  • 0 and 1 return themselves.
  • Official samples: 4 returns 2, 8 returns 2.
  • Integer.MAX_VALUE returns 46340.

Follow-ups

  • Koko Eating Bananas is the same search-the-answer idea on a feasibility check, rather than on a square.

Tests 4 returns 2. 8 returns 2. 0 returns 0. 1 returns 1. Integer.MAX_VALUE returns 46340.

How to say it in the interview "I binary-search the largest mid whose square is at most x. I compute the product in a long so it cannot overflow, and I start the high bound at x / 2. Zero and one are their own roots. Logarithmic in x."

Sources (3)
  1. LeetCode 69: Sqrt(x)leetcode.com
  2. Java SE 17 API: Integer.MAX_VALUEdocs.oracle.com
  3. JLS 17, 5.1.2: Widening primitive conversiondocs.oracle.com