Algo-Sim › Binary Search
Sqrt(x)
Easy · Binary Search · step through it in Java, Python and C++ on your own input
Binary search on the answer: the largest m with m · m ≤ x, testing mid ≤ x / mid so the square never overflows.
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.
Constraints
- 0 ≤ x ≤ 2³¹ − 1
Edge cases to test
- x = 0 and x = 1
- A perfect square
x = 2³¹ − 1(overflow inmid · mid)
Follow-up questions
- How do you avoid overflow?
- Compare
mid ≤ x / midor use 64-bit products. - Is there a faster method?
- Newton’s method
r = (r + x / r) / 2converges quadratically: O(log log x) iterations in practice. - What if you need decimals?
- Binary search on doubles for a fixed number of iterations (or until hi − lo < ε): about 60 rounds for full double precision.
Solution
Java
public 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;
if (mid <= x / mid) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}Python
def my_sqrt(x):
if x < 2: return x
lo, hi, ans = 1, x // 2, 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if mid <= x // mid:
ans = mid
lo = mid + 1
else:
hi = mid - 1
return ansC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
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;
if (mid <= x / mid) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
};
More Binary Search problems
- Binary Search (Easy)
- Search Insert Position (Easy)
- Find First and Last Position of Element in Sorted Array (Medium)
- Find Minimum in Rotated Sorted Array (Medium)
- Search in Rotated Sorted Array (Medium)
- Find Peak Element (Medium)
- Single Element in a Sorted Array (Medium)
- Koko Eating Bananas (Medium)
- Kth Smallest Element in a Sorted Matrix (Medium)
- Allocate Minimum Pages (Hard)
- Median of Two Sorted Arrays (Hard)
- Time Based Key-Value Store (Medium)