</>

69. Sqrt(x)

Easy
Binary Search Time O(log x) Space O(1)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Binary Search
Time
O(log x)
Space
O(1)

Standard Solution (C++)

SummaryGiven a non-negative integer x, compute the integer square root — the largest integer k such that k*k <= x — without using any built-in exponent or square-root functions.

Approach
  • Binary search over the candidate answer range [0, x/2] (any answer larger than x/2 is impossible for x >= 2).
  • At each midpoint mid, compare mid against x / mid using integer division to avoid overflow (never compute mid * mid directly).
  • When the search window closes, right holds the largest integer whose square does not exceed x, which is the floor of the true square root.
#include <climits>
using namespace std;

class Solution {
public:
    int mySqrt(int x) {
        // Base cases: sqrt(0)=0, sqrt(1)=1
        if (x < 2) return x;

        int lo = 1, hi = x / 2;   // answer is always <= x/2 for x >= 4
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            // Use division to avoid int overflow instead of mid*mid
            int div = x / mid;
            if (div == mid) {
                return mid;        // exact perfect square
            } else if (div > mid) {
                lo = mid + 1;      // mid is too small
            } else {
                hi = mid - 1;      // mid is too large
            }
        }
        // hi is the largest integer with hi*hi <= x
        return hi;
    }
};
Time O(log x) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int mySqrt(int x) {
        if(x<2){
            return x;
        }
        int left=2;
        int right=x/2;

        while(left<=right){
            int mid=left+(right-left)/2;
            if(x/mid>mid){
                left=mid+1;
            }
            else if(x/mid<mid){
                right=mid-1;
            }
            else{
                return mid;
            }
        }
        return right;
    }
};

// Time Complexity: O(log x)
// Space Complexity: O(1)
Time O(log x) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern