#1718
Construct the Lexicographically Largest Valid Sequence
MediumArrayBacktrackingBacktrackingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach constructs the sequence directly by placing the numbers in a specific order that guarantees the largest lexicographical order while satisfying the distance constraints. This avoids the need for permutations and checks.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty list of size 2n with -1 to represent the sequence.
- 2Step 2: Start placing numbers from n down to 2, ensuring that each number i is placed such that the distance between its two occurrences is exactly i.
- 3Step 3: Place 1 in the middle of the sequence.
solution.py8 lines
1def largest_sequence_optimal(n):
2 seq = [-1] * (2 * n)
3 for i in range(n, 1, -1):
4 first = seq.index(-1)
5 seq[first] = i
6 seq[first + i] = i
7 seq[seq.index(-1)] = 1
8 return seqℹ
Complexity note: The time complexity is O(n) because we iterate through the numbers from n down to 2 and place them in the sequence, which takes linear time.
- 1The placement of numbers must consider both the distance and the lexicographical order.
- 2Using a greedy approach helps in constructing the sequence directly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.