#932
Beautiful Array
MediumArrayMathDivide and ConquerDivide and ConquerRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a divide-and-conquer strategy to construct the beautiful array directly. By separating odd and even numbers, we ensure that the condition for a beautiful array is satisfied without needing to check every permutation.
⚙️
Algorithm
3 steps- 1Step 1: If n is 1, return [1].
- 2Step 2: Recursively build the beautiful array for n/2 and n/2 + n%2 (odd/even).
- 3Step 3: Combine the results by placing odds first followed by evens.
solution.py7 lines
1# Full working Python code
2def beautifulArray(n):
3 if n == 1:
4 return [1]
5 odds = beautifulArray((n + 1) // 2)
6 evens = beautifulArray(n // 2)
7 return odds + [x + len(odds) for x in evens]ℹ
Complexity note: The time complexity is O(n) because we build the array recursively, and each level of recursion processes a linear number of elements. The space complexity is also O(n) due to the recursion stack and the resulting array.
- 1Using divide-and-conquer can simplify complex problems.
- 2Understanding the properties of permutations helps in constructing solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.