# Program to construct the lexicographically largest valid sequence in Python

Suppose we have a number n, we have to find a sequence that satisfies all of the following rules −

• 1 occurs once in the sequence.

• Each number in between 2 and n occurs twice in the sequence.

• For every i in range 2 to 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 |j - i|. We have to find the lexicographically largest sequence.

So, if the input is like n = 4, then the output will be [4, 2, 3, 2, 4, 3, 1]

To solve this, we will follow these steps −

• Define a function backtrack() . This will take elems, res, start := 0
• if size of elems <= 0, then
• return True
• if start >= size of res , then
• return False
• if res[start] is not same as -1, then
• return backtrack(elems, res, start + 1)
• for i in range 0 to size of elems - 1, do
• num := elems[i]
• dist := 0 when num is same as 1 otherwise num
• if (start + dist) < size of res and res[start + dist] is same as -1, then
• res[start] := num
• res[start + dist] := num
• delete ith element from elems
• if backtrack(elems, res, start) is false, then
• res[start] := -1
• res[start + dist] := -1
• insert num into elems at position i
• go for next iteration
• otherwise,
• return True
• From the main method, do the following
• elems := a list with n elements from n down to 1
• res := a list of size n*2-1 and fill with -1
• backtrack(elems, res)
• return res

## Example

Let us see the following implementation to get better understanding −

def backtrack(elems, res, start = 0):
if len(elems) <= 0:
return True

if start >= len(res):
return False

if res[start] != -1:
return backtrack(elems, res, start + 1)

for i in range(len(elems)):
num = elems[i]
dist = 0 if num == 1 else num

if (start + dist) < len(res) and res[start + dist] == -1:
res[start] = num
res[start + dist] = num
elems.pop(i)

if not backtrack(elems, res, start):
res[start] = -1
res[start + dist] = -1
elems.insert(i, num)
continue
else:
return True
def solve(n):
elems = [ i for i in range(n,0,-1)]
res = [ -1 for i in range(n*2 - 1)]
backtrack(elems, res)
return res

n = 4
print(solve(n))

## Input

4

## Output

[4, 2, 3, 2, 4, 3, 1]

Updated on: 06-Oct-2021

177 Views 