[LeetCode] Form Array by Concatenating Subarrays of Another Array

1764. Form Array by Concatenating Subarrays of Another Array

You are given a 2D integer array groups of length n. You are also given an integer array nums.

You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups).

Return true if you can do this task, and false otherwise.

Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
string toString(vector<int>& A) {
string res = "#";
for(auto& a : A) {
res += to_string(a) + '#';
}
return res;
}
vector<int> PI(string& s) {
int n = s.length();
vector<int> pi(n);
for(int i = 1, j = 0; i < n; i++) {
while(j > 0 and s[i] != s[j]) j = pi[j - 1];
if(s[i] == s[j]) pi[i] = ++j;
}
return pi;
}
int kmp(string& s, string& p, int st) {
auto pi = PI(p);
for(int i = st, j = 0; i < s.length(); i++) {
while(j > 0 and s[i] != p[j]) j = pi[j - 1];
if(s[i] == p[j])
if(++j == p.length())
return i;
}

return -1;
}
public:
bool canChoose(vector<vector<int>>& groups, vector<int>& nums) {
string s = toString(nums);
int i = 0;
for(auto& g : groups) {
string p = toString(g);
i = kmp(s, p, i);
if(i == -1) return false;
i -= 1;
}


return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/24/PS/LeetCode/form-array-by-concatenating-subarrays-of-another-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.