Beautiful Arrangement II - Problem
Beautiful Arrangement II is a fascinating array construction problem that challenges you to create a specific pattern of differences between adjacent elements.
๐ฏ The Challenge: Given two integers
๐ What you're doing: If your array is
Example: For
๐ฏ The Challenge: Given two integers
n and k, you need to construct an array of n different positive integers (ranging from 1 to n) such that the absolute differences between adjacent elements produce exactly k distinct values.๐ What you're doing: If your array is
[aโ, aโ, aโ, ..., aโ], then the difference array [|aโ - aโ|, |aโ - aโ|, |aโ - aโ|, ..., |aโโโ - aโ|] must contain exactly k unique values.Example: For
n=4, k=2, one valid answer is [1,2,4,3] because the differences are [1,2,1] which has exactly 2 distinct values: {1, 2}. Input & Output
example_1.py โ Basic Case
$
Input:
n = 4, k = 2
โบ
Output:
[1, 4, 2, 3]
๐ก Note:
The differences are |1-4|=3, |4-2|=2, |2-3|=1. We have 3 differences but only 2 distinct values {2, 3} if we consider the optimal construction pattern. Actually, this gives us {1, 2, 3} which has 3 distinct values. A better answer is [1, 2, 4, 3] giving differences [1, 2, 1] with exactly 2 distinct values: {1, 2}.
example_2.py โ Minimum Case
$
Input:
n = 3, k = 1
โบ
Output:
[1, 2, 3]
๐ก Note:
When k=1, we need exactly 1 distinct difference. The array [1, 2, 3] gives differences [1, 1], which has exactly 1 distinct value: {1}.
example_3.py โ Maximum Differences
$
Input:
n = 5, k = 4
โบ
Output:
[1, 5, 2, 4, 3]
๐ก Note:
Using the alternating pattern: differences are |1-5|=4, |5-2|=3, |2-4|=2, |4-3|=1. This gives us exactly 4 distinct values: {1, 2, 3, 4}.
Constraints
- 1 โค k < n โค 104
- The array must contain all integers from 1 to n exactly once
- k must be less than n (since maximum possible distinct differences is n-1)
Visualization
Tap to expand
Understanding the Visualization
1
๐ผ Set the Range
Like a piano with keys 1 to n, position your hands at both ends
2
๐น Alternate Extremes
Play alternating high-low pattern: creates maximum interval variety efficiently
3
๐ Count Intervals
Each alternation creates a new interval size: n-1, n-2, n-3, etc.
4
๐ต Fill with Scale
Once you have k intervals, complete the melody with a simple scale
Key Takeaway
๐ฏ Key Insight: The alternating extremes pattern is like creating dramatic musical intervals - by jumping between the highest and lowest available notes, we efficiently generate exactly the number of distinct intervals we need, then complete the melody smoothly.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code