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 1 occurs once in the sequence.
  • Each integer between 2 and n occurs twice in the sequence.
  • For every integer i between 2 and n, the distance between the two occurrences of i is exactly i.
  • The distance between two numbers on the sequence, a[i] and a[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
Construct Lexicographically Largest Valid Sequencen = 3InputDistance Requirements:• Number 1 appears once• Number 2 appears twice, distance = 2• Number 3 appears twice, distance = 3Constraints312323's distance = 3 ✓2's distance = 2 ✓Lexicographically Largest: [3,1,2,3,2]
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
Asked in
Google 25 Facebook 18 Amazon 12
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen