Ctrl K

Pieces in Order Inside an Array

Medium
You are given a list of pieces (each a non-empty array of integers) and an array values. Decide whether every piece can be found in values so that: - each piece pieces[i] exactly matches some contiguous stretch of values; - the stretches come in the same order as the pieces: the one for pieces[i] lies strictly to the left of the one for pieces[i + 1]; - the stretches do not overlap, so each element of values belongs to at most one of them. Return True if this is possible and False otherwise.
Example 1
pieces=[[4, 4], [2, -1]], values=[3, 4, 4, 0, 2, -1, 5] → True

[4, 4] sits at indices 1–2 and [2, -1] at indices 4–5: the pieces are in order and do not overlap.

Example 2
pieces=[[2, -1], [4, 4]], values=[3, 4, 4, 0, 2, -1, 5] → False

The same pieces in reverse order: once [2, -1] is found, there is no 4, 4 after it.

Example 3
pieces=[[7, 7], [7]], values=[7, 7] → False

Together the pieces need three non-overlapping 7s, but the array has only two.

Constraints
  • 1 ≤ len(pieces) ≤ 1000
  • 1 ≤ len(pieces[i]), total length of the pieces ≤ 1000
  • 1 ≤ len(values) ≤ 1000
  • -10⁷ ≤ pieces[i][j], values[k] ≤ 10⁷
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Boards Holding Water MediumStudios for Recording Sessions MediumFix the Middle of the Line MediumStick Triples That Form a Triangle MediumBest-Paid Gig for Each Worker Medium
loading Python…
Input
pieces=[[4, 4], [2, -1]], values=[3, 4, 4, 0, 2, -1, 5]
Expected
True

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