Coder's Cat

LeetCode: Check Array Formation Through Concatenation

2020-12-11

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 not allowed to reorder the integers in each array pieces[i].

Return true if it is possible to form the array arr from pieces. Otherwise, return false.

Example 1:

Input: arr = [85], pieces = [[85]]
Output: true

Example 2:

Input: arr = [15,88], pieces = [[88],[15]]
Output: true

Explanation: Concatenate [15] then [88]

CPP solution

Note all the integers in arr and pieces are distinct, so we use a ordered_map to store the relationships between first element and index.
Then iterate all elements in arr to check whether each element is same with arrays in pieces.

Time complexity: O(N), where N is the size of arr.

class Solution {
public:
bool canFormArray(vector<int>& arr, vector<vector<int>>& pieces) {
unordered_map<int, int> info;
int count = 0;
for(int i=0; i<pieces.size(); i++) {
int head = pieces[i][0];
info[head] = i;
count += pieces[i].size();
}
if(count != arr.size()) return false;
int index = 0;
while(index < arr.size()) {
int v = arr[index];
if(info.find(v) == info.end())
return false;
vector<int>& vec = pieces[info[v]];
for(auto& v: vec) {
if(index >= arr.size() || arr[index++] != v)
return false;
}
}
return true;
}
};

Java Solution

class Solution {
public boolean canFormArray(int[] arr, int[][] pieces) {
Map<Integer, int[]> map = new HashMap<>();
for (int[] piece : pieces) {
map.put(piece[0], piece);
}

//iterate all the elements in arr
for (int i = 0; i < arr.length; ) {
int curVal = arr[i];
if (map.containsKey(curVal)) {
int[] piece = map.get(curVal);
for (int value : piece) {
if (arr[i] == value) {
i++;
} else {
return false;
}
}
} else {
return false;
}
}
return true;
}
}

Preparing for an interview? Checkout this!