Check Array Formation Through Concatenation - Problem

Imagine you're a puzzle master with a target array of distinct integers and a collection of puzzle pieces (smaller arrays). Your challenge is to determine if you can form the exact target array by arranging these pieces in any order you want!

Here's the twist: while you can rearrange the pieces themselves, you cannot change the order of numbers within each piece. It's like having puzzle pieces where the internal pattern is fixed, but you can place the pieces anywhere in the final picture.

Goal: Return true if you can perfectly reconstruct the target array using all the pieces, false otherwise.

Example: If arr = [15,88] and pieces = [[88],[15]], you can rearrange pieces to get [15,88] โœ…

Input & Output

example_1.py โ€” Basic Rearrangement
$ Input: arr = [15,88], pieces = [[88],[15]]
โ€บ Output: true
๐Ÿ’ก Note: We can rearrange pieces as [[15],[88]] to form [15,88] by concatenation
example_2.py โ€” Multi-element Pieces
$ Input: arr = [49,18,16], pieces = [[16,18,49]]
โ€บ Output: false
๐Ÿ’ก Note: The piece [16,18,49] cannot form [49,18,16] because we cannot reorder elements within pieces
example_3.py โ€” Multiple Pieces
$ Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]
โ€บ Output: true
๐Ÿ’ก Note: Rearrange pieces as [[91],[4,64],[78]] to get [91,4,64,78]

Visualization

Tap to expand
Car 15Car 88Target Train: [15, 88]Car 88Car 15Available GroupsCar Directory15 โ†’ Group with Car 1588 โ†’ Group with Car 88Build Directory1Lookup 152Lookup 88โœ“ Success!๐ŸŽฏ Key Insight: Use first element as unique identifier for instant piece lookup!
Understanding the Visualization
1
Catalog Car Groups
Create a directory of all car groups by their lead car number
2
Walk the Target Train
Start from the front and identify each expected car group
3
Validate Each Group
Check that each car group matches exactly as expected
4
Success Check
If all groups match, the train can be assembled
Key Takeaway
๐ŸŽฏ Key Insight: The first element of each piece serves as a unique identifier, enabling O(1) lookups and O(n) total time complexity!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through target array (n elements) with O(1) hash map lookups

n
2n
โœ“ Linear Growth
Space Complexity
O(p)

Hash map stores p pieces, where p is number of pieces

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค pieces.length โ‰ค arr.length โ‰ค 100
  • Sum of pieces[i].length equals arr.length
  • 1 โ‰ค pieces[i].length โ‰ค arr.length
  • 1 โ‰ค arr[i], pieces[i][j] โ‰ค 100
  • All integers in arr are distinct
  • All integers in pieces are distinct
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
28.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen