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

# Permutation Sequence Python Solution

> Tested Python solution for LeetCode 60 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 60, [Hard](/catalog/hard). Topics: [Math](/catalog/topics/math), [Recursion](/catalog/topics/recursion). [View on LeetCode](https://leetcode.com/problems/permutation-sequence/description/).

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

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

## Problem

The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations.

By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`:

* `"123"`
* `"132"`
* `"213"`
* `"231"`
* `"312"`
* `"321"`

Given `n` and `k`, return the `kth` permutation sequence.

### Examples

```
Input: Input: n = 3, k = 3
Output: "213"
```

```
Input: Input: n = 4, k = 9
Output: "2314"
```

```
Input: Input: n = 3, k = 1
Output: "123"
```

### Constraints

* `1 <= n <= 9`
* `1 <= k <= n!`

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import math


class Solution:
    # Time: O(n^2)
    # Space: O(n)
    def get_permutation(self, n: int, k: int) -> str:
        digits = [str(i) for i in range(1, n + 1)]
        remaining = k - 1
        parts: list[str] = []
        for i in range(n, 0, -1):
            block_size = math.factorial(i - 1)
            idx, remaining = divmod(remaining, block_size)
            parts.append(digits.pop(idx))
        return "".join(parts)
```

## Complexity

| Time   | Space |
| ------ | ----- |
| O(n^2) | O(n)  |

## Tags
