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 the array arr
by concatenating the arrays in pieces
in any order. However, you cannot reorder the integers in each subarray in pieces
.
Return True
if you can form the array arr
by concatenating the arrays in pieces
. Otherwise, return False
.
arr
and each subarray of pieces
unique?
arr
and pieces
are distinct.pieces
be used only once?
pieces
can only be used once.arr
and pieces
?
arr
is in the range [1, 100]
.pieces
is in the range [1, 100]
.With these clarifications in mind, let’s plan our solution.
To solve this problem, we will follow these steps:
pieces
to the subarray itself.arr
while trying to match each segment of arr
with one of the subarrays in pieces
as denoted by the dictionary.False
.arr
, return True
.def can_form_array(arr, pieces):
# Create a dictionary with the first element of each subarray in pieces as the key
piece_dict = {piece[0]: piece for piece in pieces}
i = 0
while i < len(arr):
if arr[i] not in piece_dict:
return False
piece = piece_dict[arr[i]]
# Check if the piece matches the segment of arr starting at index i
if arr[i:i+len(piece)] != piece:
return False
i += len(piece)
return True
# Example Usage
arr = [85, 1, 2, 3, 101]
pieces = [[85], [1, 2, 3], [101]]
print(can_form_array(arr, pieces)) # Expected Output: True
pieces
.arr
and checking segments takes (O(m)) where (m) is the length of arr
.Thus, the final time complexity of the solution is (O(m + n)) which is efficient given the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?