Sequence Reconstruction
1 approach, code in every language
Problem description
You are given an integer array nums that is a permutation of the numbers from 1 to n. You are also given a collection of sequences, where each sequence is a list of integers drawn from those same values.
A valid supersequence is any ordering of the numbers 1 through n such that every given sequence appears within it as a subsequence, meaning its elements occur in the same relative order though not necessarily adjacent.
Determine whether nums is the one and only sequence that can be reconstructed as the shortest supersequence of all the given sequences. Return true if nums is uniquely reconstructable, and false otherwise.
Example 1
Input: nums = [1,2,3], sequences = [[1,2],[1,3]]
Output: false
We know 1 comes before both 2 and 3, but the order of 2 and 3 is unconstrained, so both [1,2,3] and [1,3,2] are valid; the reconstruction is not unique.
Example 2
Input: nums = [1,2,3], sequences = [[1,2],[1,3],[2,3]]
Output: true
The edges force 1 before 2, 1 before 3, and 2 before 3, which pins the order to exactly [1,2,3].
Constraints
n == nums.length1 <= n <= 10^4nums is a permutation of the integers from 1 to n.1 <= sequences.length <= 10^41 <= sum of sequences[i].length <= 10^51 <= sequences[i][j] <= n
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Is the Running Order Forced is our own problem on the technique behind Sequence Reconstruction: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free