Ctrl K

Order Forced by Fragments

Medium
The list order is a permutation of the numbers 1 to n. You also get a set of fragments fragments: each fragment is a subsequence of order, that is, some of its numbers in the same relative order (not necessarily adjacent). Call a sequence fitting if every fragment is a subsequence of it. Among all fitting sequences, look at the shortest ones. Return True if order is the one and only shortest fitting sequence, and False otherwise.
Example 1
order=[2, 1, 3], fragments=[[2, 1], [1, 3]] → True

The fragments chain into 2 → 1 → 3 with no other option, so the answer is True.

Example 2
order=[2, 1, 3], fragments=[[2, 1], [2, 3]] → False

All we know is that 2 comes before both 1 and 3. The order [2, 3, 1] fits just as well, so the answer is False.

Example 3
order=[1, 2, 3, 4], fragments=[[1, 2, 3]] → False

The number 4 appears in no fragment, so the shortest fitting sequence is [1, 2, 3], not order. The answer is False.

Constraints
  • n == order.length
  • 1 ≤ n ≤ 10⁴
  • order is a permutation of the numbers 1 to n
  • 1 ≤ fragments.length ≤ 10⁴
  • 1 ≤ fragments[i].length ≤ 10⁴
  • the total length of all fragments is at most 10⁵
  • all fragments are distinct
  • each fragments[i] is a subsequence of order
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsQuietest of the Richer MediumDishes You Can Cook MediumExpand a Template With Variables MediumLetter Order From a Dictionary HardLongest Uphill Walk Hard
loading Python…
Input
order=[2, 1, 3], fragments=[[2, 1], [1, 3]]
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 77 tests on the server, hidden ones included.