Intuition
To find the square root of a number x
, we need the largest integer n
such that (n^2 \leq x). Since the square root is monotonic (i.e., increasing as x
increases), binary search is a natural choice to efficiently find the answer without testing every possible value from 0
to x
.
Approach
Binary Search Setup:
Initialize
left
to0
andright
tox
. The answer will lie between these two values.Use a variable
result
to store the current best approximation of the square root.
Binary Search Execution:
Calculate the mid-point
mid
as ((\text{left} + \text{right}) // 2).If ( \text{mid}^2 > x ), the square root must be smaller, so adjust the
right
boundary tomid - 1
.If ( \text{mid}^2 < x ), the square root must be larger, so adjust the
left
boundary tomid + 1
and updateresult
tomid
(current best approximation).If ( \text{mid}^2 == x ), return
mid
directly as it’s an exact match.
Return Approximation:
- After the loop, return the
result
, which will contain the largest integer (n) such that (n^2 \leq x).
- After the loop, return the
Complexity
Time complexity:
$$O(\log x)$$
The binary search reduces the search space by half at each iteration, resulting in a logarithmic time complexity.Space complexity:
$$O(1)$$
The solution uses a constant amount of extra space, regardless of the size ofx
.
Code
class Solution(object):
def mySqrt(self, x):
left, right = 0, x
result = 0
while left <= right:
mid = (left + right) // 2
if mid**2 > x:
right = mid - 1
elif mid**2 < x:
left = mid + 1
result = mid
else:
return mid
return result
Example Test Cases
Input:
x = 4
Output:2
Explanation: The square root of 4 is exactly 2.Input:
x = 8
Output:2
Explanation: The square root of 8 is approximately 2.83, and the largest integer less than or equal to 2.83 is 2.Input:
x = 0
Output:0
Explanation: The square root of 0 is 0.Input:
x = 1
Output:1
Explanation: The square root of 1 is exactly 1.
Connect with Me
If you found this solution helpful, feel free to connect with me on LinkedIn! Let’s grow and share knowledge together. 😊