Check Array Formation Through Concatenation
To check whether we can form the given array arr
by concatenating the arrays in pieces
without reordering the integers in each array, we can follow these steps:
- Create a dictionary
mapping
that maps the first element of each piece to its corresponding array. - Iterate through
arr
, and for each element, check if it exists inmapping
. If it does, then check if the subsequent elements inarr
match the elements in the corresponding piece. If not, returnFalse
. - Return
True
if all elements inarr
match the elements in the corresponding pieces.
Implementation
Python solution:
|
|
Explanation
- For Input:
arr = [15,88], pieces = [[88],[15]]
- Mapping:
{15: [15], 88: [88]}
- Iteration through
arr
:[15]
then[88]
- Output:
true
This code ensures that each piece is used exactly as it appears in pieces
and in the order that corresponds to arr
. The complexity of this solution is ( O(n) ), where ( n ) is the length of arr
, as it iterates through arr
and performs constant-time operations for each element.