Beautiful Array - Problem
Beautiful Array Construction
Imagine you need to construct a special permutation of numbers from 1 to n called a beautiful array. This array has a unique mathematical property: no three elements can form an arithmetic progression when you pick any two elements and check if there's a middle element that's their average.
More formally, an array
•
• For every
Your task is to construct and return any beautiful array of length n. The mathematical guarantee ensures that at least one solution always exists!
Imagine you need to construct a special permutation of numbers from 1 to n called a beautiful array. This array has a unique mathematical property: no three elements can form an arithmetic progression when you pick any two elements and check if there's a middle element that's their average.
More formally, an array
nums of length n is beautiful if:•
nums is a permutation of integers [1, 2, ..., n]• For every
0 ≤ i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j]Your task is to construct and return any beautiful array of length n. The mathematical guarantee ensures that at least one solution always exists!
Input & Output
example_1.py — Small Case
$
Input:
n = 4
›
Output:
[1, 3, 2, 4]
💡 Note:
This is a valid beautiful array because no element is the average of two others positioned further apart. For example, there's no k where 2*nums[k] equals nums[i] + nums[j] for i < k < j.
example_2.py — Single Element
$
Input:
n = 1
›
Output:
[1]
💡 Note:
Base case: A single element array is always beautiful since there are no triplets to check.
example_3.py — Larger Case
$
Input:
n = 5
›
Output:
[1, 5, 3, 2, 4]
💡 Note:
Another valid beautiful array. The divide-and-conquer approach generates odds [1,5,3] from transforming [1,3,2] and evens [2,4] from transforming [1,2], then concatenates them.
Visualization
Tap to expand
Understanding the Visualization
1
Divide
Split the problem: create beautiful arrangements for smaller groups
2
Transform Odds
Apply 2*x-1 to get odd positions (ensures no averaging with evens)
3
Transform Evens
Apply 2*x to get even positions (maintains beautiful property)
4
Conquer
Combine odds + evens safely (mathematical guarantee of beauty)
Key Takeaway
🎯 Key Insight: By separating odds and evens through mathematical transformations, we guarantee that no odd number can be the average of any two numbers in our array, making it safe to combine beautiful subsequences into a larger beautiful array!
Time & Space Complexity
Time Complexity
O(n! * n³)
O(n!) permutations, each requiring O(n³) checks for all triplets
⚠ Quadratic Growth
Space Complexity
O(n)
Space for storing current permutation and recursion stack
⚡ Linearithmic Space
Constraints
- 1 ≤ n ≤ 1000
- nums must be a permutation of [1, 2, ..., n]
- No arithmetic progression: 2 * nums[k] ≠ nums[i] + nums[j] for i < k < j
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code