69. Sqrt(x)

MathBinary Search

Explanation

To find the square root of a non-negative integer x without using any built-in exponent function or operator, we can use binary search. We start with a range [0, x] and iteratively narrow down the range until we find the square root. At each iteration, we calculate the mid-point of the current range and check if the square of the mid-point is greater, equal to, or less than x. Based on this comparison, we update the range to search in. We continue this process until we find the integer square root.

  • Algorithm:

    1. Initialize left to 0 and right to x.
    2. While left <= right, calculate the mid-point mid as (left + right) / 2.
    3. If mid * mid == x, return mid.
    4. If mid * mid < x, update left to mid + 1.
    5. If mid * mid > x, update right to mid - 1.
    6. Return right as the integer square root of x.
  • Time Complexity: O(log(x)) - Binary search reduces the search range by half in each iteration.

  • Space Complexity: O(1) - Constant extra space is used.

class Solution {
    public int mySqrt(int x) {
        if (x == 0) return 0;
        long left = 1, right = x;
        while (left < right) {
            long mid = left + (right - left) / 2;
            if (mid * mid == x) return (int)mid;
            else if (mid * mid < x) left = mid + 1;
            else right = mid;
        }
        return (int)right - 1;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.