Construct the Lexicographically Largest Valid Sequence

Medium Topics Company Tags

Build an array using the integers from 1 through n. The value 1 appears once, and every value k from 2 through n appears twice. The two copies of k must occupy indices whose difference is exactly k. Return the lexicographically largest valid array: at the first position where two arrays differ, prefer the one with the larger value. The array has length 2*n-1, and a valid answer always exists.

Example 1:

Input: n = 1

Output: [1]

Explanation: Only the value 1 is available, and it appears once. The sole valid array is [1].

Example 2:

Input: n = 2

Output: [2,1,2]

Explanation: The two copies of 2 occupy indices 0 and 2, whose difference is 2. The remaining position holds 1, yielding [2,1,2].

Example 3:

Input: n = 4

Output: [4,2,3,2,4,3,1]

Explanation: In [4,2,3,2,4,3,1], the copies of 4 are four positions apart, the copies of 3 are three apart, and the copies of 2 are two apart. Starting with 4 and then 3 cannot be completed legally; starting with 4 and then 2 gives this largest valid array.

Constraints:

  • 1 <= n <= 20


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.