Leetcode 1640. Check Array Formation Through Concatenation
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 only allowed to concatenate whole arrays in pieces and cannot reorder the integers within any individual piece array.
Return True if you can form the array arr from pieces. Otherwise, return False.
Input: arr = [85], pieces = [[85]]
Output: true
Input: arr = [15,88], pieces = [[88],[15]]
Output: true
Input: arr = [49,18,16], pieces = [[16,18,49]]
Output: false
Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]
Output: true
1 <= pieces.length <= arr.length <= 100sum(pieces[i].length) == arr.length1 <= arr[i], pieces[i][j] <= 100arr are distinct.pieces are distinct (i.e., no integer is repeated).arr and pieces exactly once?
arr and pieces are distinct and each integer will appear exactly once.pieces?
arr, the order must match exactly as in arr.arr in both values and order.To solve this problem, follow these steps:
pieces and the value is the entire subarray.arr and for each element, check if it is the starting element of any subarray in the hashmap.arr with the subarray.arr.arr are matched successfully, return True. Else, return False.import java.util.HashMap;
class Solution {
public boolean canFormArray(int[] arr, int[][] pieces) {
HashMap<Integer, int[]> map = new HashMap<>();
// Store each piece's first element as key and the piece itself as value
for (int[] piece : pieces) {
map.put(piece[0], piece);
}
int i = 0;
while (i < arr.length) {
// If arr[i] is not a starting number of any piece, return false
if (!map.containsKey(arr[i])) {
return false;
}
// Get the piece associated with arr[i]
int[] piece = map.get(arr[i]);
for (int j = 0; j < piece.length; j++) {
// Check if the current sequence in arr matches with the piece
if (arr[i] != piece[j]) {
return false;
}
i++; // Move to the next element in arr
}
}
return true; // All elements matched
}
}
pieces.arr.Overall, the time complexity is O(n + m), which makes the solution efficient for the given constraints.
The space complexity is also minimal, mainly for the hashmap and the input array storage, which is O(n).
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?