Form Array by Concatenating Subarrays of Another Array LeetCode solution in C++
1class Solution {2public:3// Idea is to use KMP Longest Prefix Suffix array to match if one array is4// subarray of another array.5bool canChoose(vector<vector<int>> &groups, vector<int> &nums) {6int m = nums.size();7int index = 0;8for (auto group : groups) {9int n = group.size();10// Step-1 Generate LPS11vector<int> lps(n, 0);12for (int i = 1; i < n; i++) {13int j = lps[i - 1];14while (j > 0 && group[i] != group[j]) {15j = lps[j - 1];16}17if (group[i] == group[j]) {18j++;19}20lps[i] = j;21}2223// Step 2 - Matching24int j = 0;25while (index < m) {26if (nums[index] == group[j]) {27j++;28index++;29}30if (j == n)31break;32else if (index < m && nums[index] != group[j]) {33if (j > 0) {34j = lps[j - 1];35} else {36index++;37}38}39}40if (j != n) return false;41}4243return true;44}45};