Check Array Formation Through Concatenation Problem
Description
LeetCode Problem 1640.
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.
Example 1:
Input: arr = [15,88], pieces = [[88],[15]]
Output: true
Explanation: Concatenate [15] then [88]
Example 2:
Input: arr = [49,18,16], pieces = [[16,18,49]]
Output: false
Explanation: Even though the numbers match, we cannot reorder pieces[0].
Example 3:
Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]
Output: true
Explanation: Concatenate [91] then [4,64] then [78]
Constraints:
1 <= pieces.length <= arr.length <= 100sum(pieces[i].length) == arr.length1 <= pieces[i].length <= arr.length1 <= arr[i], pieces[i][j] <= 100- The integers in
arrare distinct. - The integers in
piecesare distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
Solution
Approach: Look Up Each Piece by Its First Number
All numbers are distinct, so at any position of arr at most one piece can start there: the piece whose first number is arr[i]. Map each piece's first number to the piece.
Walk through arr from index 0:
- If no piece starts with
arr[i],arrcannot be formed. - Otherwise that piece must appear right here, in its own order, so compare it with
arr[i], arr[i+1], .... On a mismatch (or ifarrends too early), returnfalse; otherwise jump past the piece.
Reaching the end of arr means it is a concatenation of pieces. Because the total length of the pieces equals arr.length and all numbers are distinct, no piece is used twice or left out.
Complexity: O(n) time and O(p) extra space for the map, where n is the length of arr and p the number of pieces.
class Solution:
def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:
# All numbers are distinct, so each piece is identified by its first number.
by_first = {p[0]: p for p in pieces}
i = 0
while i < len(arr):
p = by_first.get(arr[i])
if p is None or arr[i:i + len(p)] != p:
return False
i += len(p)
return True