Sequence Reconstruction

update Jul 18, 2017 15:35

lintcodearrow-up-right

Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 10^4. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequence so that all sequences in seqs are subsequences of it). Determine whether there is only one sequence that can be reconstructed from seqs and it is the org sequence.

Example

Given org = [1,2,3], seqs = [[1,2],[1,3]]
Return false
Explanation:
[1,2,3] is not the only one sequence that can be reconstructed, 
because [1,3,2] is also a valid sequence that can be reconstructed.

Given org = [1,2,3], seqs = [[1,2]]
Return false
Explanation:
The reconstructed sequence can only be [1,2].

Given org = [1,2,3], seqs = [[1,2],[1,3],[2,3]]
Return true
Explanation:
The sequences [1,2], [1,3], and [2,3] can uniquely reconstruct 
the original sequence [1,2,3].

Given org = [4,1,5,2,6,3], seqs = [[5,2,6,3],[4,1,5,2]]
Return true

Basic Idea:

这道题其实就是求是否有唯一的topological sort的结果。什么情况下会有不止一种结果呢?就是当某一时刻有不止一个indegree为0的node的时候。所以我们只需要监测queue.size() > 1即可。当然,在这之前要根据 seqs 生成 Map<Integer, List<Integer>> 形式的 graph;

具体的,有一些非法输入的情况需要handle。

Java Code:

Python Code:

update Aug 29, 2019

再记录一个更加快速的解法,不用contruct graph,而是从边出发。我们先从给定的所有seq中获得所有solid的edge,检查每个edge是否vialate给定的org array顺序。又因为必须是唯一存在的顺序,之后也要检查从前到后每一对org中元素相对顺序是否有对应的edge在seqs中出现。

例如:

另外还有一些特殊情况要处理。

Last updated