|
| 1 | +""" |
| 2 | +Easy |
| 3 | +1640. [Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation/) |
| 4 | +
|
| 5 | +You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are |
| 6 | +distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to |
| 7 | +reorder the integers in each array pieces[i]. |
| 8 | +
|
| 9 | +Return true if it is possible to form the array arr from pieces. Otherwise, return false. |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +Input: arr = [85], pieces = [[85]] |
| 13 | +Output: true |
| 14 | +
|
| 15 | +Example 2: |
| 16 | +Input: arr = [15,88], pieces = [[88],[15]] |
| 17 | +Output: true |
| 18 | +Explanation: Concatenate [15] then [88] |
| 19 | +
|
| 20 | +Example 3: |
| 21 | +Input: arr = [49,18,16], pieces = [[16,18,49]] |
| 22 | +Output: false |
| 23 | +Explanation: Even though the numbers match, we cannot reorder pieces[0]. |
| 24 | +
|
| 25 | +Example 4: |
| 26 | +Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]] |
| 27 | +Output: true |
| 28 | +Explanation: Concatenate [91] then [4,64] then [78] |
| 29 | +
|
| 30 | +Example 5: |
| 31 | +Input: arr = [1,3,5,7], pieces = [[2,4,6,8]] |
| 32 | +Output: false |
| 33 | +
|
| 34 | +Constraints: |
| 35 | +1 <= pieces.length <= arr.length <= 100 |
| 36 | +sum(pieces[i].length) == arr.length |
| 37 | +1 <= pieces[i].length <= arr.length |
| 38 | +1 <= arr[i], pieces[i][j] <= 100 |
| 39 | +The integers in arr are distinct. |
| 40 | +The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct). |
| 41 | +""" |
| 42 | + |
| 43 | +# Solutions |
| 44 | + |
| 45 | + |
| 46 | +class Solution: |
| 47 | + """ |
| 48 | + len(arr) = m |
| 49 | + len(pieces) = n |
| 50 | + Time Complexity: O( max(m, n) ) |
| 51 | + Space Complexity: O( n ) |
| 52 | + """ |
| 53 | + |
| 54 | + def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: |
| 55 | + d = {x[0]: x for x in pieces} |
| 56 | + |
| 57 | + ind = 0 |
| 58 | + while ind < len(arr): |
| 59 | + value = d.get(arr[ind]) |
| 60 | + if not value or arr[ind : ind + len(value)] != value: |
| 61 | + return False |
| 62 | + ind += len(value) |
| 63 | + |
| 64 | + return True |
| 65 | + |
| 66 | + |
| 67 | +# Runtime : 28 ms, faster than 99.69% of Python3 online submissions |
| 68 | +# Memory Usage : 14.5 MB, less than 16.74% of Python3 online submissions |
0 commit comments