Problem Description
Given a permutation array nums and a list of subsequences, sequences, determine if nums is the only shortest supersequence that contains every sequence in sequences as a subsequence. In other words, by using the ordering constraints from each subsequence, check if there exists exactly one way (that equals nums) to reconstruct the full sequence using the minimum number of elements.
Key Insights
- The problem requires reconstructing the sequence using ordering constraints, making it natural to use topological sorting.
- Build a directed graph where an edge u -> v signifies that u comes before v.
- Count indegrees for each node; nodes with zero indegree are eligible to appear next in the sequence.
- The reconstruction is unique if at every step there is exactly one candidate with indegree 0.
- Finally, ensure the reconstructed order exactly matches nums.
Space and Time Complexity
Time Complexity: O(N + M), where N is the number of elements in nums and M is the total number of elements in sequences. Space Complexity: O(N + M) due to the graph, indegree array/map, and auxiliary data structures.
Solution
The solution uses a graph-based approach, specifically employing topological sort to determine the order of nodes. First, construct a graph and compute indegree counts by iterating through each subsequence in sequences. Then, perform a topological sort: add nodes with indegree 0 to a queue and process them one by one. If at any point more than one node is available (queue size greater than one), the reconstruction is not unique so return false. Additionally, as you pop each node, verify that it coincides with the corresponding element in the given nums. If the complete reconstructed order matches nums and no ambiguities were encountered during the sort, return true. Otherwise, return false.
Code Solutions
Below are code solutions in Python, JavaScript, C++, and Java with line-by-line comments.