Sequence Reconstruction - Problem
Sequence Reconstruction is a fascinating problem that challenges you to determine if a given sequence is the unique shortest supersequence for a set of subsequences.
You're given:
โข An integer array
โข A 2D array
Your task is to determine if
Think of it as a puzzle: given several incomplete clues about the order of elements, can you uniquely determine the complete sequence? For example, if sequences = [[1,2],[1,3]], both [1,2,3] and [1,3,2] work as shortest supersequences, so the answer is false. But if sequences = [[1,2],[1,3],[1,2,3]], only [1,2,3] works uniquely!
You're given:
โข An integer array
nums of length n where nums is a permutation of integers [1, n]โข A 2D array
sequences where each sequences[i] is a subsequence of numsYour task is to determine if
nums is both the shortest possible and the only supersequence that contains all given subsequences.Think of it as a puzzle: given several incomplete clues about the order of elements, can you uniquely determine the complete sequence? For example, if sequences = [[1,2],[1,3]], both [1,2,3] and [1,3,2] work as shortest supersequences, so the answer is false. But if sequences = [[1,2],[1,3],[1,2,3]], only [1,2,3] works uniquely!
Input & Output
example_1.py โ Basic Unique Case
$
Input:
nums = [1,2,3], sequences = [[1,2],[1,3]]
โบ
Output:
false
๐ก Note:
Both [1,2,3] and [1,3,2] are valid shortest supersequences. Since nums is not the unique shortest supersequence, return false.
example_2.py โ Constrained Unique Case
$
Input:
nums = [1,2,3], sequences = [[1,2],[1,3],[2,3]]
โบ
Output:
true
๐ก Note:
The sequences force the order: 1โ2, 1โ3, and 2โ3. This uniquely determines [1,2,3] as the only possible shortest supersequence.
example_3.py โ Invalid Reconstruction
$
Input:
nums = [4,1,5,2,6,3], sequences = [[5,2,6,3],[4,1,5,2]]
โบ
Output:
false
๐ก Note:
The given sequences don't provide enough constraints to uniquely determine nums as the only shortest supersequence.
Constraints
- 1 โค nums.length โค 104
- nums.length == n
- nums is a permutation of all integers in range [1, n]
- 1 โค sequences.length โค 104
- 1 โค sequences[i].length โค 104
- All values in sequences[i] are in range [1, n]
- sequences[i] are subsequences of nums
Visualization
Tap to expand
Understanding the Visualization
1
Build Dependency Graph
From sequences like [1,2] and [2,3], create edges 1โ2 and 2โ3
2
Count Prerequisites
Calculate in-degree for each node (how many dependencies it has)
3
Process in Order
At each step, exactly one item should be ready (in-degree 0)
4
Verify Uniqueness
If multiple items are ready simultaneously, reconstruction isn't unique
Key Takeaway
๐ฏ Key Insight: A sequence reconstruction is unique if and only if at each step of topological sorting, exactly one node has in-degree 0. Multiple nodes with in-degree 0 means multiple valid orderings exist.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code