Check Array Formation Through Concatenation - Problem

You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i].

Return true if it is possible to form the array arr from pieces. Otherwise, return false.

Input & Output

Example 1 — Basic Case
$ Input: arr = [85], pieces = [[85]]
Output: true
💡 Note: Single piece [85] exactly matches the target array [85]
Example 2 — Multiple Pieces
$ Input: arr = [15,88], pieces = [[88],[15]]
Output: true
💡 Note: Can rearrange pieces: [15] + [88] = [15,88] matches target
Example 3 — Impossible Case
$ Input: arr = [49,18,16], pieces = [[16,18,49]]
Output: false
💡 Note: Piece [16,18,49] cannot be reordered to match [49,18,16]

Constraints

  • 1 ≤ pieces.length ≤ arr.length ≤ 100
  • sum(pieces[i].length) == arr.length
  • 1 ≤ pieces[i].length ≤ arr.length
  • 1 ≤ arr[i], pieces[i][j] ≤ 100
  • The integers in arr are distinct
  • The integers in pieces are distinct

Visualization

Tap to expand
Check Array Formation Through Concatenation INPUT Array arr: 85 arr[0] Array pieces: pieces[0] 85 Input Values: arr = [85] pieces = [[85]] ALGORITHM STEPS 1 Build Hash Map Map first element of each piece to piece 85 --> [85] 2 Iterate arr Check each element exists in map 3 Match Piece 85 found in map piece = [85] 4 Verify Match arr[0]=85 matches piece[0]=85 All elements matched! FINAL RESULT Formation Check: Target: arr [85] = pieces[0] [85] Output: true OK - Array can be formed from pieces! Key Insight: Using a hash map with first element as key allows O(1) lookup for each piece. Since all integers are distinct, each element uniquely identifies its piece, enabling efficient matching. Time complexity: O(n) where n is total elements in arr. TutorialsPoint - Check Array Formation Through Concatenation | Hash Map Lookup Approach
Asked in
Amazon 15 Google 8
28.0K Views
Medium Frequency
~15 min Avg. Time
920 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