644. Spaced Sequence
Build a sequence of length 2n - 1 that follows these rules: the number 1 appears exactly once; each number from 2 to n appears exactly twice; and the two copies of a number i (for i >= 2) are exactly i positions apart, i.e. their indices differ by i.
Return the lexicographically largest sequence that obeys these rules (the one that has the larger number at the first position where two candidates differ). A valid sequence always exists for the allowed values of n.
Example 1
- Input:
- n = 3
- Output:
- [3,1,2,3,2]
- Explanation:
The sequence
[3, 1, 2, 3, 2]has the two 3s three positions apart and the two 2s two positions apart. No valid sequence starts with a larger number.
Example 2
- Input:
- n = 1
- Output:
- [1]
- Explanation:
The single number 1 appears once.
Example 3
- Input:
- n = 2
- Output:
- [2,1,2]
- Explanation:
[2, 1, 2]: the two 2s are two positions apart.
Constraints
- 1 ≤
n≤ 20
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms
Expected complexity
- Time
- exponential in the worst case, tiny in practice
- Space
- O(n)