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 −
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))
[4, 2, 3, 2, 4, 3, 1]