> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Sqrt(x) Python Solution with Tests

> Tested Python solution for LeetCode 69 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 69, Easy. Topics: Math, Binary Search. [View on LeetCode](https://leetcode.com/problems/sqrtx/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 69   # by problem number
lcpy gen -s sqrtx   # by problem name
```

## 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.

You **must not use** any built-in exponent function or operator.

* For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python.

### Examples

```
Input: x = 4
Output: 2
```

**Explanation:** The square root of 4 is 2, so we return 2.

```
Input: x = 8
Output: 2
```

**Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.

### Constraints

* 0 \<= x \<= 2^31 - 1

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/sqrtx/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/sqrtx/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(log x)
    # Space: O(1)
    def my_sqrt(self, x: int) -> int:
        if x < 2:
            return x

        left = 0
        right = x

        while left < right:
            mid = (left + right) // 2
            if mid * mid <= x < (mid + 1) * (mid + 1):
                return mid
            elif mid * mid > x:
                right = mid
            else:
                left = mid + 1

        return left
```

## Complexity

| Time     | Space |
| -------- | ----- |
| O(log x) | O(1)  |

## Tags

[NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
