Construct the Lexicographically Largest Valid Sequence - Problem
Given an integer n, find a sequence with elements in the range [1, n] that satisfies all of the following conditions:
- The integer
1occurs once in the sequence. - Each integer between
2andnoccurs twice in the sequence. - For every integer
ibetween2andn, the distance between the two occurrences ofiis exactlyi. - The distance between two numbers on the sequence,
a[i]anda[j], is the absolute difference of their indices,|j - i|.
Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution.
A sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b. For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5.
Input & Output
Example 1 — Small Case
$
Input:
n = 3
›
Output:
[3,1,2,3,2]
💡 Note:
For n=3, we need sequence with 1 once, 2 twice, 3 twice. Distance between two 2's is |3-1|=2 ✓, distance between two 3's is |4-0|=4≠3 ✗. Correct answer: [3,1,2,3,2] where 2's are at positions 2,4 (distance 2) and 3's are at positions 0,3 (distance 3).
Example 2 — Minimum Case
$
Input:
n = 1
›
Output:
[1]
💡 Note:
For n=1, only need number 1 once. The sequence is simply [1].
Example 3 — Medium Case
$
Input:
n = 4
›
Output:
[4,1,3,1,2,4,2]
💡 Note:
For n=4: 1 occurs once, 2,3,4 occur twice each. All distance constraints satisfied: 2's at distance 2, 3's at distance 3, 4's at distance 4. This is the lexicographically largest valid sequence.
Constraints
- 1 ≤ n ≤ 20
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given n=3, need sequence with specific distance rules
2
Requirements
1 appears once, 2 and 3 appear twice each, with distance constraints
3
Output
Lexicographically largest valid sequence [3,1,2,3,2]
Key Takeaway
🎯 Key Insight: Use backtracking with greedy placement (try larger numbers first) to build the lexicographically largest sequence while satisfying distance constraints
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code