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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code