MediumNo. 0932

Beautiful Array — LeetCode 932 Python Solution

Topics
Array, Math, Divide and Conquer
Reading time
2 min

The 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].

Example

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

Python solution

PythonSolution
class Solution:
    def beautifulArray(self, n: int) -> List[int]:
        if n == 1:
            return [1]
        left = self.beautifulArray((n + 1) >> 1)
        right = self.beautifulArray(n >> 1)
        left = [x * 2 - 1 for x in left]
        right = [x * 2 for x in right]
        return left + right

Complexity

Time
O(n) or O(1)
Space · auxiliary
O(1)

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 932. Beautiful Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0927Three Equal PartsHard
0048Rotate ImageMedium
0066Plus OneEasy
0189Rotate ArrayMedium
0204Count PrimesMedium
0335Self CrossingHard

Frequently asked questions

How hard is LeetCode 932. Beautiful Array?

LeetCode 932. Beautiful Array is rated Medium on LeetCode.

What topics does LeetCode 932. Beautiful Array cover?

LeetCode 932. Beautiful Array is tagged Array, Math and Divide and Conquer on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.