Problem
Given an integer n
, find a sequence that satisfies all of the following:
- The integer
1
occurs once in the sequence. - Each integer between
2
andn
occurs twice in the sequence. - For every integer
i
between2
andn
, the distance between the two occurrences ofi
is 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
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= n <= 20
Solution
Method 1 - Backtracking
The problem asks for constructing a sequence meeting the described conditions. The sequence must satisfy three major constraints, and we must also make it lexicographically largest. Here’s the reasoning:
Approach
- Backtracking and Placement Strategy:
- Start with an empty array of size
(2 * n - 1)
since:1
occurs once.- All integers
2
ton
occur twice. - Between the two occurrences of
i
, their distance is exactlyi
, so the sequence length is determined by2n - 1
.
- Place
n
first to maximise the sequence lexicographically, then placen-1
, and so on until1
.
- Start with an empty array of size
- Constraints Check:
- For each
i
where2 <= i <= n
, ensure the two indices wherei
is placed have a difference ofi
exactly. Place1
wherever feasible since it occurs only once.
- For each
- Backtracking:
- Try placing each number from highest (
n
) to lowest (1
). - If a number cannot be placed (due to overlaps or constraint violations), backtrack and try alternative placements.
- Try placing each number from highest (
- Base Case:
- If all numbers are placed correctly, return the sequence.
- Lexicographical Order:
- By placing larger numbers first (
n → 1
), the sequence will naturally be lexicographically largest.
- By placing larger numbers first (
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n!)
- The complexity arises from the recursive backtracking. In the worst case, the solution will explore multiple placements but has a clear upper bound since the sequence is fixed in length.
O(n!)
in the extreme worst case due to the factorial nature of placements, but optimised heavily by constraints and pruning.
- 🧺 Space complexity:
O(n)
, wheren
is the recursion stack at peak (containing numbers to be placed in the sequence).