Problem Description
Given an integer n, construct a sequence of length (2n - 1) with numbers in the range [1, n] such that:
- The number 1 appears exactly once.
- For each number i (2 ≤ i ≤ n), it appears exactly twice.
- For each i (2 ≤ i ≤ n), the distance (absolute difference in indices) between its two occurrences is exactly i. Among all valid sequences, return the lexicographically largest one.
Key Insights
- To achieve the lexicographically largest sequence, try to place larger numbers as early as possible.
- Since numbers must be placed exactly twice (except for 1, which is placed once), when placing a number i (i > 1), reserve two positions: one at index pos and the other at index pos+i, ensuring the required gap.
- Use backtracking to try placements while following the sequence constraints.
- Use a global state (or shared data structure) to mark numbers as used.
- Skip already filled positions to reduce unnecessary work during recursion.
Space and Time Complexity
Time Complexity: Exponential in the worst-case due to backtracking; however, the constrained n (1 ≤ n ≤ 20) keeps the problem tractable. Space Complexity: O(n) for the recursion stack and an auxiliary array of size O(2n).
Solution
We solve this problem using a backtracking approach. We create an array of size (2n - 1) initialized with a placeholder value (e.g. -1) to indicate unfilled positions. Then we recursively try to place numbers from n down to 1 (to favor lexicographically larger sequences) as follows:
- For each unfilled index, attempt to put a number that hasn’t been used:
- If the number is 1, it requires only one position.
- For numbers greater than 1, ensure that the partner position (current index + i) is available and within bounds.
- Mark the number as used, place it (and its partner for numbers > 1), and move to the next index.
- If the placement leads to a dead-end, backtrack by unmarking the number and resetting the positions.
- The algorithm stops when all positions are filled, ensuring the lexicographically largest valid sequence.