Beautiful Arrangement II - Problem

Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement:

Suppose this list is answer = [a₁, a₂, a₃, ..., aₙ], then the list [|a₁ - a₂|, |a₂ - a₃|, |a₃ - a₄|, ..., |aₙ₋₁ - aₙ|] has exactly k distinct integers.

Return the list answer. If there are multiple valid answers, return any of them.

Input & Output

Example 1 — Basic Case
$ Input: n = 4, k = 3
Output: [1,4,2,3]
💡 Note: Differences are |1-4|=3, |4-2|=2, |2-3|=1, giving exactly 3 distinct values {1,2,3}
Example 2 — Small k
$ Input: n = 5, k = 2
Output: [1,5,2,3,4]
💡 Note: Differences are |1-5|=4, |5-2|=3, |2-3|=1, |3-4|=1, giving exactly 2 distinct values {1,3}
Example 3 — Minimum Case
$ Input: n = 2, k = 1
Output: [1,2]
💡 Note: Only one difference |1-2|=1, exactly k=1 distinct value

Constraints

  • 1 ≤ k < n ≤ 104

Visualization

Tap to expand
Beautiful Arrangement II: Create Array with k Distinct DifferencesInput: n=4, k=3Need 4 numbers3 distinct diffsConstruction: [1,4,2,3]1423Differences321|1-4| = 3, |4-2| = 2, |2-3| = 1Success! Exactly k=3 distinct differences: {1, 2, 3}
Understanding the Visualization
1
Input
Given n=4, k=3, need array of [1,2,3,4] with 3 distinct differences
2
Construction
Alternate between min/max: [1,4,2,3]
3
Verification
Differences: 3,2,1 - exactly k=3 distinct values
Key Takeaway
🎯 Key Insight: Alternating between minimum and maximum remaining values creates all differences 1,2,3...k efficiently
Asked in
Google 35 Facebook 28 Amazon 22
28.0K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen