|
| 1 | +""" |
| 2 | +Problem Link: https://leetcode.com/problems/check-array-formation-through-concatenation/ |
| 3 | +
|
| 4 | +You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. |
| 5 | +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]. |
| 6 | +Return true if it is possible to form the array arr from pieces. Otherwise, return false. |
| 7 | +
|
| 8 | +Example 1: |
| 9 | +Input: arr = [85], pieces = [[85]] |
| 10 | +Output: true |
| 11 | +
|
| 12 | +Example 2: |
| 13 | +Input: arr = [15,88], pieces = [[88],[15]] |
| 14 | +Output: true |
| 15 | +Explanation: Concatenate [15] then [88] |
| 16 | +
|
| 17 | +Example 3: |
| 18 | +Input: arr = [49,18,16], pieces = [[16,18,49]] |
| 19 | +Output: false |
| 20 | +Explanation: Even though the numbers match, we cannot reorder pieces[0]. |
| 21 | +
|
| 22 | +Example 4: |
| 23 | +Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]] |
| 24 | +Output: true |
| 25 | +Explanation: Concatenate [91] then [4,64] then [78] |
| 26 | +
|
| 27 | +Example 5: |
| 28 | +Input: arr = [1,3,5,7], pieces = [[2,4,6,8]] |
| 29 | +Output: false |
| 30 | + |
| 31 | +Constraints: |
| 32 | +1 <= pieces.length <= arr.length <= 100 |
| 33 | +sum(pieces[i].length) == arr.length |
| 34 | +1 <= pieces[i].length <= arr.length |
| 35 | +1 <= arr[i], pieces[i][j] <= 100 |
| 36 | +The integers in arr are distinct. |
| 37 | +The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct). |
| 38 | +""" |
| 39 | +class Solution: |
| 40 | + def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: |
| 41 | + indexes = {arr[i]: i for i in range(len(arr))} |
| 42 | + |
| 43 | + for piece in pieces: |
| 44 | + prev_index = None |
| 45 | + |
| 46 | + for element in piece: |
| 47 | + cur_index = indexes.get(element) |
| 48 | + if (prev_index is not None and cur_index != prev_index + 1) or cur_index is None: |
| 49 | + return False |
| 50 | + |
| 51 | + prev_index = cur_index |
| 52 | + indexes[element] = None |
| 53 | + |
| 54 | + return True |
0 commit comments