Skip to content

Sqrt(x)

Given a non-negative integer x, return the square root of x rounded down to the nearest integer.

You need to solve this problem efficiently.

InputOutputExplanation
Example 1Result 1Explanation for example 1
Example 2Result 2Explanation for example 2
  • Constraint 1 for Sqrt(x)
  • Constraint 2
  • Constraint 3
ApproachTimeSpaceBest When
Binary SearchO(n)O(1)When applicable
NewtonO(n)O(1)When applicable
IterativeO(n)O(1)When applicable
★ Recommended

This approach provides an efficient solution for sqrt(x).

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
sqrtx_binary_search.py
def sqrtx_binary_search(x: int) -> int:
"""Find integer square root using binary search."""
if x < 2:
return x
left, right = 2, x // 2
while left <= right:
mid = (left + right) // 2
if mid * mid == x:
return mid
elif mid * mid < x:
left = mid + 1
else:
right = mid - 1
return right
# Test cases
print(sqrtx_binary_search(4)) # 2
print(sqrtx_binary_search(8)) # 2
🎯 Interview Favourite

This approach provides an efficient solution for sqrt(x).

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
sqrtx_newton.py
# Python Solution
# Problem: sqrtx
# Approach: newton
# Implementation placeholder for sqrtx_newton
# This file is auto-generated and should contain the solution code.
def sqrtx_newton():
pass
if __name__ == "__main__":
pass
✓ Simple

This approach provides an efficient solution for sqrt(x).

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
sqrtx_iterative.py
# Python Solution
# Problem: sqrtx
# Approach: iterative
# Implementation placeholder for sqrtx_iterative
# This file is auto-generated and should contain the solution code.
def sqrtx_iterative():
pass
if __name__ == "__main__":
pass