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

# Beautiful Array Python Solution with Tests

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

LeetCode 932, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Math](/catalog/topics/math), [Divide and Conquer](/catalog/topics/divide-and-conquer). [View on LeetCode](https://leetcode.com/problems/beautiful-array/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 932   # by problem number
lcpy gen -s beautiful_array   # by problem name
```

## Problem

An array `nums` of length `n` is **beautiful** if:

* `nums` is a permutation of the integers in the range `[1, n]`.
* For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`.

Given the integer `n`, return any **beautiful** array `nums` of length `n`. There will be at least one valid answer for the given `n`.

### Examples

```
Input: n = 4
Output: [2,1,4,3]
```

```
Input: n = 5
Output: [3,1,2,5,4]
```

### Constraints

* `1 <= n <= 1000`

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(n)
    def beautiful_array(self, n: int) -> list[int]:
        # Divide and conquer: odds and evens of a beautiful array are each
        # beautiful, and concatenating two beautiful halves never creates a
        # bad triple since 2 * nums[k] == nums[i] + nums[j] requires nums[i]
        # and nums[j] of the same parity while k sits in the other half.
        res = [1]
        while len(res) < n:
            res = [2 * x - 1 for x in res] + [2 * x for x in res]
        return [x for x in res if x <= n]
```

## Complexity

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

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.