Sqrt(x) — LeetCode 69 Python Solution
- Problem
- #69
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.
Example
- Input
- x = 4
- Output
- 2
- Explanation
- The square root of 4 is 2, so we return 2.
Python solution
class Solution:
def mySqrt(self, x: int) -> int:
l, r = 0, x
while l < r:
mid = (l + r + 1) >> 1
if mid > x // mid:
r = mid - 1
else:
l = mid
return lComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log x) |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 69. Sqrt(x) is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
On a study list
This problem is on Top Interview 150.
Frequently asked questions
- How hard is LeetCode 69. Sqrt(x)?
- LeetCode 69. Sqrt(x) is rated Easy on LeetCode.
- What is the time complexity of LeetCode 69. Sqrt(x)?
- The Python solution on this page runs in O(\log x).
- What is the space complexity of LeetCode 69. Sqrt(x)?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 69. Sqrt(x) cover?
- LeetCode 69. Sqrt(x) is tagged Math and Binary Search on LeetCode.