|
| 1 | +/** |
| 2 | + * 1718. Construct the Lexicographically Largest Valid Sequence |
| 3 | + * https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given an integer n, find a sequence that satisfies all of the following: |
| 7 | + * - The integer 1 occurs once in the sequence. |
| 8 | + * - Each integer between 2 and n occurs twice in the sequence. |
| 9 | + * - For every integer i between 2 and n, the distance between the two occurrences of i is |
| 10 | + * exactly i. |
| 11 | + * |
| 12 | + * The distance between two numbers on the sequence, a[i] and a[j], is the absolute difference |
| 13 | + * of their indices, |j - i|. |
| 14 | + * |
| 15 | + * Return the lexicographically largest sequence. It is guaranteed that under the given |
| 16 | + * constraints, there is always a solution. |
| 17 | + * |
| 18 | + * A sequence a is lexicographically larger than a sequence b (of the same length) if in the first |
| 19 | + * position where a and b differ, sequence a has a number greater than the corresponding number in |
| 20 | + * b. For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position |
| 21 | + * they differ is at the third number, and 9 is greater than 5. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number} n |
| 26 | + * @return {number[]} |
| 27 | + */ |
| 28 | +var constructDistancedSequence = function(n) { |
| 29 | + const result = new Array(2 * n - 1).fill(0); |
| 30 | + const group = new Array(n + 1).fill(false); |
| 31 | + |
| 32 | + backtrack(0); |
| 33 | + |
| 34 | + function backtrack(index) { |
| 35 | + if (index === 2 * n - 1) { |
| 36 | + return true; |
| 37 | + } else if (result[index] !== 0) { |
| 38 | + return backtrack(index + 1); |
| 39 | + } |
| 40 | + for (let num = n; num >= 1; num--) { |
| 41 | + if (group[num]) { |
| 42 | + continue; |
| 43 | + } |
| 44 | + group[num] = true; |
| 45 | + result[index] = num; |
| 46 | + if (num === 1 || (index + num < 2 * n - 1 && result[index + num] === 0)) { |
| 47 | + if (num > 1) { |
| 48 | + result[index + num] = num; |
| 49 | + } |
| 50 | + if (backtrack(index + 1)) { |
| 51 | + return true; |
| 52 | + } |
| 53 | + if (num > 1) { |
| 54 | + result[index + num] = 0; |
| 55 | + } |
| 56 | + } |
| 57 | + result[index] = 0; |
| 58 | + group[num] = false; |
| 59 | + } |
| 60 | + return false; |
| 61 | + } |
| 62 | + |
| 63 | + return result; |
| 64 | +}; |
0 commit comments