Ctrl K

Exactly k Kinds of Gaps

Medium
You are given n and k. Arrange the numbers 1 to n (each exactly once) into a sequence whose absolute differences between neighbours take exactly k distinct values. There are usually many such sequences, so build this particular one: 1. Take the first k elements alternately from the numbers still unused: first the smallest, then the largest, then the smallest again, and so on. 2. Append the remaining numbers, continuing from the same side as the k-th element: in increasing order if it was the smallest unused number, in decreasing order if it was the largest. Return the resulting sequence. Make sure it really has exactly k distinct gaps.
Example 1
n=6, k=3 → [1, 6, 2, 3, 4, 5]

In turn: 1 (smallest), 6 (largest), 2 (smallest). The last pick was the smallest, so 3, 4, 5 follow. The gaps are 5, 4, 1, 1, 1: three distinct values.

Example 2
n=5, k=2 → [1, 5, 4, 3, 2]

1, then 5; the last pick was the largest, so 4, 3, 2 follow. The gaps are 4, 1, 1, 1: two distinct values.

Example 3
n=4, k=1 → [1, 2, 3, 4]
Constraints
  • 1 ≤ k < n ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTurn a Square Clockwise MediumPostfix Calculator MediumRoll an Array to the Right MediumPrimes Below a Bound MediumNth Number Built From Given Primes Medium
loading Python…
Input
n=6, k=3
Expected
[1, 6, 2, 3, 4, 5]

Run checks the first 3 tests in your browser. Submit checks all 74 tests on the server, hidden ones included.