|
| 1 | +/** |
| 2 | + * 444. Sequence Reconstruction |
| 3 | + * https://leetcode.com/problems/sequence-reconstruction/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an integer array nums of length n where nums is a permutation of the |
| 7 | + * integers in the range [1, n]. You are also given a 2D integer array sequences where |
| 8 | + * sequences[i] is a subsequence of nums. |
| 9 | + * |
| 10 | + * Check if nums is the shortest possible and the only supersequence. The shortest |
| 11 | + * supersequence is a sequence with the shortest length and has all sequences[i] as |
| 12 | + * subsequences. There could be multiple valid supersequences for the given array sequences. |
| 13 | + * - For example, for sequences = [[1,2],[1,3]], there are two shortest supersequences, |
| 14 | + * [1,2,3] and [1,3,2]. |
| 15 | + * - While for sequences = [[1,2],[1,3],[1,2,3]], the only shortest supersequence possible |
| 16 | + * is [1,2,3]. [1,2,3,4] is a possible supersequence but not the shortest. |
| 17 | + * |
| 18 | + * Return true if nums is the only shortest supersequence for sequences, or false otherwise. |
| 19 | + * |
| 20 | + * A subsequence is a sequence that can be derived from another sequence by deleting some or |
| 21 | + * no elements without changing the order of the remaining elements. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number[]} nums |
| 26 | + * @param {number[][]} sequences |
| 27 | + * @return {boolean} |
| 28 | + */ |
| 29 | +var sequenceReconstruction = function(nums, sequences) { |
| 30 | + const n = nums.length; |
| 31 | + const graph = new Map(); |
| 32 | + const inDegree = new Array(n + 1).fill(0); |
| 33 | + |
| 34 | + for (let i = 1; i <= n; i++) { |
| 35 | + graph.set(i, []); |
| 36 | + } |
| 37 | + |
| 38 | + for (const seq of sequences) { |
| 39 | + for (let i = 1; i < seq.length; i++) { |
| 40 | + graph.get(seq[i - 1]).push(seq[i]); |
| 41 | + inDegree[seq[i]]++; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + const queue = []; |
| 46 | + for (let i = 1; i <= n; i++) { |
| 47 | + if (inDegree[i] === 0) { |
| 48 | + queue.push(i); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + if (queue.length !== 1) return false; |
| 53 | + |
| 54 | + const result = []; |
| 55 | + while (queue.length) { |
| 56 | + if (queue.length > 1) return false; |
| 57 | + const curr = queue.shift(); |
| 58 | + result.push(curr); |
| 59 | + |
| 60 | + const nextNodes = graph.get(curr); |
| 61 | + for (const next of nextNodes) { |
| 62 | + inDegree[next]--; |
| 63 | + if (inDegree[next] === 0) { |
| 64 | + queue.push(next); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return result.length === n && result.every((val, i) => val === nums[i]); |
| 70 | +}; |
0 commit comments