Construct the Lexicographically Largest Valid Sequence Problem
Description
LeetCode Problem 1718.
Given an integer n, find a sequence with elements in the range [1, n] that satisfies all of the following:
- 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] 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.
Example 1:
Input: n = 3
Output: [3,1,2,3,2]
Explanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.
Example 2:
Input: n = 5
Output: [5,3,1,4,3,5,2,4,2]
Constraints:
1 <= n <= 20
Solution
Approach: Backtracking
The sequence has length 2n - 1: 1 appears once, and every i from 2 to n appears twice, exactly i positions apart. With n <= 20, backtracking is fast enough.
To get the lexicographically largest sequence, fill the positions from left to right and try the largest values first. At an empty position u, try i from n down to 2: if i is still unused and position u + i is free and inside the sequence, place i at both u and u + i, and continue with the next position. If that fails, undo it and try the next value; finally try 1, which needs only position u. The first complete sequence found is the answer.
path holds the placed values and cnt how many copies of each value are still to be placed.
Complexity: exponential in the worst case, but the search is very small for n <= 20.
class Solution:
def constructDistancedSequence(self, n: int) -> List[int]:
def dfs(u):
if u == n * 2:
return True
if path[u]:
return dfs(u + 1)
for i in range(n, 1, -1):
if cnt[i] and u + i < n * 2 and path[u + i] == 0:
cnt[i] = 0
path[u] = path[u + i] = i
if dfs(u + 1):
return True
path[u] = path[u + i] = 0
cnt[i] = 2
if cnt[1]:
cnt[1], path[u] = 0, 1
if dfs(u + 1):
return True
path[u], cnt[1] = 0, 1
return False
path = [0] * (n * 2)
cnt = [2] * (n * 2)
cnt[1] = 1
dfs(1)
return path[1:]