Sqrt(x)
LeetCode 69 · Easy · solution, intuition & step-by-step walkthrough
Binary search for the last m with m² ≤ x.
This is how I solved Sqrt(x) (LeetCode 69), an easy problem from the Basics / Lower & Upper Bound pattern. Below: the intuition, the approach step by step, my accepted Python code and the 2 versions I wrote on the way, animated test cases and a line-by-line debugger.
Intuition
The integer square root is the largest m with m² ≤ x. Squares grow monotonically, so binary search over m: too big → search lower, too small → search higher. When the loop ends, high is the answer.
Approach
- 1
Linear scan works but is O(√x).
- 2
Binary search on [1, x].
- 3
mid² == x → return mid; > x → high = mid − 1; else low = mid + 1.
- 4
Return high.
How I solved it · from first idea to final
Try every i.
Floor of the square root.
Linear scanPythonO(√x) time
#TC- O(sqrt of N)
class Solution:
def mySqrt(self, x: int) -> int:
for i in range(x+1):
if i*i==x:
return i
elif (i*i)>x:
return i-1Binary searchPythonO(log x) time · O(1) space
class Solution:
def getAnsRange(self,ans, x):
ans = ans*ans
if ans==x:
return 1
elif ans>x:
return 2
else:
return 0
def mySqrt(self, x: int) -> int:
if x<2:
return x
low = 1
high = x
while low<=high:
mid = (low+high)//2
range = self.getAnsRange(mid,x)
if range==1:
return mid
elif range==2:
high=mid-1
else:
low = mid+1
return highSqrt(x) — FAQ
What is the intuition behind Sqrt(x)?
The integer square root is the largest m with m² ≤ x. Squares grow monotonically, so binary search over m: too big → search lower, too small → search higher. When the loop ends, high is the answer.
How do you solve Sqrt(x) (LeetCode 69)?
1. Linear scan works but is O(√x). 2. Binary search on [1, x]. 3. mid² == x → return mid; > x → high = mid − 1; else low = mid + 1. 4. Return high.
What is the time and space complexity of Sqrt(x)?
Time: O(log x). Space: O(1). (Accepted approach: Binary search.)
What are common mistakes in Sqrt(x)?
x < 2 returns x directly.
Is there more than one way to solve Sqrt(x)?
Linear scan (O(√x) time): Try every i. Binary search (O(log x) time · O(1) space): Floor of the square root.