Construct the Lexicographically Largest Valid Sequence
Given an integer n, build an array of length 2n - 1 that satisfies all of these rules:
- The value
1appears exactly once. - Every value from
2throughnappears exactly twice. - For every value
xfrom2throughn, the two occurrences ofxare exactlyxpositions apart, so if one occurrence sits at indexi, the other sits at indexi + x.
Return the lexicographically largest valid array.
Examples
Input: 1
Output: [1]
Input: 2
Output: [2,1,2]
Hints
Fill the array from left to right and always try the largest unused value first, because the first complete array found is the lexicographically largest.
At the first empty index, a value `x` must start there, and it needs the slot at `index + x` to be empty and inside the array.
Undo a placement and try the next smaller value whenever a branch cannot be completed.
Related Problems
Construct the Lexicographically Largest Valid Sequence
Given an integer n, build an array of length `2n - 1` that satisfies all of these rules: