LeetCode 1640: Check Array Formation Through Concatenation
Problem Description
Explanation
To solve this problem, we need to check if it is possible to form the array arr
by concatenating the arrays in pieces
without reordering the integers within each array in pieces
. We can achieve this by mapping each integer in arr
to its corresponding piece in pieces
and checking if the concatenation of these mapped pieces matches the original arr
.
We can create a mapping of the first integer of each piece to the entire piece. Then, we iterate through arr
, check if the integer is in our mapping, and concatenate the corresponding piece. If at any point we encounter an integer that is not in the mapping or the final concatenated array does not match arr
, we return false
.
Solutions
class Solution {
public boolean canFormArray(int[] arr, int[][] pieces) {
Map<Integer, int[]> map = new HashMap<>();
for (int[] piece : pieces) {
map.put(piece[0], piece);
}
int[] result = new int[arr.length];
int idx = 0;
for (int num : arr) {
if (map.containsKey(num)) {
int[] piece = map.get(num);
for (int i = 0; i < piece.length; i++) {
result[idx++] = piece[i];
}
} else {
return false;
}
}
return Arrays.equals(arr, result);
}
}
Loading editor...