MediumArrayGraphTopological Sort

Sequence Reconstruction

LeetCode
1 approach, code in all languages

You are given an integer array nums that is a permutation of the numbers from 1 to n. You are also given a collection of sequences, where each sequence is a list of integers drawn from those same values.

A valid supersequence is any ordering of the numbers 1 through n such that every given sequence appears within it as a subsequence, meaning its elements occur in the same relative order though not necessarily adjacent.

Determine whether nums is the one and only sequence that can be reconstructed as the shortest supersequence of all the given sequences. Return true if nums is uniquely reconstructable, and false otherwise.

Example 1

Input: nums = [1,2,3], sequences = [[1,2],[1,3]]

Output: false

We know 1 comes before both 2 and 3, but the order of 2 and 3 is unconstrained, so both [1,2,3] and [1,3,2] are valid; the reconstruction is not unique.

Example 2

Input: nums = [1,2,3], sequences = [[1,2],[1,3],[2,3]]

Output: true

The edges force 1 before 2, 1 before 3, and 2 before 3, which pins the order to exactly [1,2,3].

Constraints

  • n == nums.length
  • 1 <= n <= 10^4
  • nums is a permutation of the integers from 1 to n.
  • 1 <= sequences.length <= 10^4
  • 1 <= sum of sequences[i].length <= 10^5
  • 1 <= sequences[i][j] <= n
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now