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,3,2,4,5]
💡 Note: Differences are |1-3|=2, |3-2|=1, |2-4|=2, |4-5|=1, giving exactly 2 distinct values {1,2}
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 INPUT n = 4 k = 3 Available numbers: 1 to n 1 2 3 4 Goal: Arrange to get exactly k=3 distinct differences Need 3 unique |diff| values 1 2 3 ALGORITHM STEPS 1 Start with extremes Use 1 and n for max diff 2 Zigzag pattern Alternate low-high-low 3 Fill k differences First k+1 elements zigzag 4 Sequential remainder Rest in order (diff=1) Building Process: low=1, high=4 [1] -- pick low [1,4] -- pick high [1,4,2] -- pick low [1,4,2,3] -- pick high k=3 differences achieved! FINAL RESULT Output Array: 1 4 2 3 Differences Computed: |1-4| =3 |4-2| =2 |2-3| =1 Distinct differences: {1, 2, 3} = 3 values OK - k=3 achieved! Output: [1, 4, 2, 3] Key Insight: To create exactly k distinct differences, use a zigzag pattern alternating between low and high values. Starting with 1 and n gives difference (n-1), then shrink range inward to create k unique differences. Time: O(n) | Space: O(n) for the result array. Pattern: 1, n, 2, n-1, 3, n-2, ... until k differences. TutorialsPoint - Beautiful Arrangement II | Optimal Solution
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