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

# Perfect Squares Python Solution with Tests

> Tested Python solution for LeetCode 279 with 17 pytest cases. Generate a practice environment with lcpy.

LeetCode 279, Medium. Topics: Math, Dynamic Programming, Breadth-First Search. [View on LeetCode](https://leetcode.com/problems/perfect-squares/description/).

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

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

## Problem

Given an integer `n`, return *the least number of perfect square numbers that sum to* `n`.

A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not.

### Examples

```
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
```

```
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
```

### Constraints

* 1 \<= n \<= 10^4

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n * sqrt(n))
    # Space: O(n)
    def num_squares(self, n: int) -> int:
        dp = [0] + [n + 1] * n
        for i in range(1, n + 1):
            j = 1
            while j * j <= i:
                dp[i] = min(dp[i], dp[i - j * j] + 1)
                j += 1
        return dp[n]
```

## Complexity

| Time            | Space |
| --------------- | ----- |
| O(n \* sqrt(n)) | O(n)  |

## Tags

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