You get two integers, n and k. Arrange the numbers 1 to n, each used exactly once, in a list.
Look at the gaps between neighbours: the absolute difference of each adjacent pair. Your list must produce exactly k different gap sizes. Return any list that does.
Example 1
Input: n = 4, k = 1 Output: [1, 2, 3, 4] Why: every gap is 1, a single size
2 more examples and the constraints
Example 2
Input: n = 5, k = 4 Output: [1, 5, 2, 4, 3] Why: the gaps are 4, 3, 2, 1: four sizes
Example 3
Input: n = 4, k = 2 Output: [1, 2, 4, 3] Why: the gaps are 1, 2, 1: two sizes
Constraints
- 1 ≤ k < n ≤ 10,000
- Any valid list is accepted
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Reverse the tail k − 1 timesO(n·k)
- Count, then zigzagO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 10,000, k = 9,999 | Verdict |
|---|---|---|---|
| Reverse the tail k − 1 times | O(n·k) | Correct, rewrites the tail k times | |
| Count, then zigzag | O(n) | Best; writes each number once |
n = how many numbers, k = how many gap sizes.
Edge cases to test
- k = 1. The plain list 1, 2, …, n works; the zigzag part is just n − 1, n.
- k = n − 1. The calm part is empty; the whole list zigzags: 1, n, 2, n − 1, …
- n = 2. k must be 1, and [1, 2] has the single gap 1.
- Many valid answers. Only the count of gap sizes is checked, so any correct list passes.
Common mistakes
- Starting the zigzag at 1 instead of n − k, which makes gaps bigger than k.
- Off-by-one in the calm part, so it ends at n − k and repeats that number.
- Counting gaps with their signs instead of absolute values.
How to talk through it
- 1Clarify. Must the list use 1 to n exactly once? Is any valid answer accepted?
- 2Find a pattern on paper. 1, n, 2, n − 1, … gives the most sizes, n − 1 of them.
- 3Tune it to k. Zigzag only over the last k + 1 numbers; count up before that.
- 4Check the join. The calm part ends one below where the zigzag starts, so the join is a gap of 1.
- 5Test out loud. Run n = 4, k = 1 and n = 5, k = 4 and list the gaps.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?