Skip to main content

Construct the Lexicographically Largest Valid Sequence - Video Solutions

MediumArrayBacktracking

Construct the Lexicographically Largest Valid Sequence | Detailed | Leetcode 1718 | codestorywithMIK

codestorywithMIK
37:3913,471 views
10 video solutions available

Construct the Lexicographically Largest Valid Sequence - Video Solution

Watch 10 video solutions for Construct the Lexicographically Largest Valid Sequence, a medium level problem involving Array, Backtracking. This walkthrough by codestorywithMIK has 13,471 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.

Problem Statement

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 and n occurs twice in the sequence.
  • For every integer i between 2 and 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 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
Read full problem with examples

Approach Overview

Problem Overview: You need to build an array of length 2n - 1 using numbers from 1 to n. Each number k > 1 must appear exactly twice and the distance between the two occurrences must be k. Number 1 appears once. Among all valid sequences, return the lexicographically largest one.

Approach 1: Backtracking with Greedy Placement (Time: O(n!), Space: O(n))

This is the most common solution and the one typically expected in interviews. Use backtracking to fill the sequence from left to right. At each empty index, try placing numbers from n down to 1. For values greater than 1, you must check whether index i + k is within bounds and also empty before placing both occurrences. Mark the number as used, continue recursion, and revert the placement if it leads to a dead end. Trying larger numbers first guarantees the first valid sequence you find is already the lexicographically largest. The search space is exponential, but pruning invalid placements early keeps it manageable.

Approach 2: Iterative Construction (Time: O(n^2), Space: O(n))

An iterative strategy builds the sequence while scanning the array and attempting placements based on available numbers. Maintain a result array and a structure that tracks which numbers are still unused. When encountering an empty position, try inserting the largest remaining number that satisfies the distance constraint. This approach relies on repeated checks and adjustments as the sequence grows. It works well for moderate n values and avoids recursion overhead, though it still performs many placement validations.

Approach 3: Divide and Conquer Placement (Time: O(n!), Space: O(n))

You can model the problem as recursively solving subsegments of the array. Pick the largest unused number and attempt to place it at valid positions within the current segment. Once placed, the array splits into smaller independent segments that must also satisfy the same constraints. The recursive structure resembles divide-and-conquer: each placement reduces the problem size and creates smaller subproblems. In practice this behaves similarly to backtracking but conceptually emphasizes segment decomposition within the array.

Approach 4: Heap-based Ordering (Time: O(n log n), Space: O(n))

A heap can help prioritize which numbers to attempt first. Store unused numbers in a max-heap so the largest value is always considered before smaller ones. While scanning the sequence, extract the largest candidate and check if its required distance placement is valid. If placement fails, temporarily skip it and reinsert it later. The heap guarantees lexicographic preference toward larger numbers while maintaining efficient retrieval.

Recommended for interviews: The backtracking solution is the expected answer. Interviewers want to see how you model constraints, prune invalid states, and enforce lexicographic ordering by trying larger numbers first. Starting with brute-force placement shows understanding, but implementing efficient backtracking with early validation demonstrates strong problem-solving skills.

Complexity Analysis

ApproachTimeSpaceWhen to Use
Backtracking with Greedy PlacementO(n!)O(n)Best general solution. Guarantees lexicographically largest sequence and commonly expected in interviews.
Iterative ConstructionO(n^2)O(n)Useful when avoiding recursion or when implementing incremental construction logic.
Divide and Conquer PlacementO(n!)O(n)Conceptual recursive decomposition of the array into smaller segments.
Heap-based OrderingO(n log n)O(n)When prioritizing larger numbers efficiently using a heap structure.