Problem Description
Given an array of distinct integers arr and a collection of integer arrays pieces (with distinct integers overall), determine if arr can be formed by concatenating the arrays in pieces in any order while keeping the order of integers in each individual piece unchanged.
Key Insights
- Each integer in arr is unique; similarly, every integer in pieces is unique across all pieces.
- Use a hash map (or dictionary) to map the first element of each piece to the corresponding array.
- Iterate through arr, and for each element, if it exists as the key in our hash map, validate that the following segment in arr exactly matches the corresponding piece.
- If any element in arr does not match the start of a piece or the sequence does not match, return false.
Space and Time Complexity
Time Complexity: O(n), where n is the length of arr, since each element is processed exactly once. Space Complexity: O(m), where m is the number of pieces, due to the extra hash map.
Solution
To solve the problem, we first construct a hash map that associates the first integer of each piece with the piece itself. Then, using a pointer, we traverse arr. For each arr element, we check whether it is the starting element of a piece by looking it up in the hash map. If found, we validate that the subsequent numbers in arr match the entire piece. If there is any mismatch or an element in arr isn't found as a key in the map, we return false. If we successfully process all elements in arr, we return true. This approach efficiently leverages a hash map to match pieces in O(n) time without reordering the individual pieces.