Sequence Reconstruction - Problem

You are given an integer array nums of length n where nums is a permutation of the integers in the range [1, n]. You are also given a 2D integer array sequences where sequences[i] is a subsequence of nums.

Check if nums is the shortest possible and the only supersequence. The shortest supersequence is a sequence with the shortest length and has all sequences[i] as subsequences.

There could be multiple valid supersequences for the given array sequences. For example, for sequences = [[1,2],[1,3]], there are two shortest supersequences, [1,2,3] and [1,3,2]. While for sequences = [[1,2],[1,3],[1,2,3]], the only shortest supersequence possible is [1,2,3].

Return true if nums is the only shortest supersequence for sequences, or false otherwise.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Input & Output

Example 1 — Unique Sequence
$ Input: nums = [1,2,3], sequences = [[1,2,3],[1]]
Output: true
💡 Note: The sequences force a unique ordering: 1 must come first (from [1]), then 2, then 3 (from [1,2,3]). Only [1,2,3] satisfies all constraints.
Example 2 — Multiple Valid Orderings
$ Input: nums = [1,2,3], sequences = [[1,2],[1,3]]
Output: false
💡 Note: Both [1,2,3] and [1,3,2] satisfy the constraints. Since there are multiple valid shortest supersequences, return false.
Example 3 — Invalid Coverage
$ Input: nums = [4,1,5,2,6,3], sequences = [[5,2,6,3],[4,1,5,2]]
Output: false
💡 Note: The sequences don't provide enough constraints to uniquely determine the order between all elements.

Constraints

  • 1 ≤ n ≤ 104
  • nums is a permutation of [1, n]
  • 1 ≤ sequences.length ≤ 104
  • 1 ≤ sequences[i].length ≤ 104

Visualization

Tap to expand
Sequence Reconstruction: Verify Unique SupersequenceInputnums = [1,2,3]sequences = [[1,2,3],[1]]Build Dependencies1 → 2 → 31 has indegree 0Topological SortQueue: [1] → [2] → [3]Only one choice at each step✓ Result matches nums: [1,2,3] is unique supersequenceOutput: true
Understanding the Visualization
1
Input
nums=[1,2,3], sequences=[[1,2,3],[1]]
2
Build Graph
Create dependency graph from sequences
3
Check Uniqueness
Use topological sort to verify unique ordering
Key Takeaway
🎯 Key Insight: Use topological sort to check if there's exactly one valid ordering at each step
Asked in
Google 45 Facebook 32 Amazon 28
32.4K Views
Medium Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen