![]() |
VOOZH | about |
You are given two integer arrays a[] and b[]. Return all the starting indexes of all the occurrences of b[] as a subarray in a[].
Examples:
Input: a[] = [2, 4, 1, 0, 4, 1, 1], b[] = [4, 1]
Output: [1, 4]
Explanation: b[] occurs as a subarray in a[] from index 1 to 2 and from index 4 to 5.Input: a[] = [2, 4, 1, 0, 0, 3], b[] = [0]
Output: [3, 4]
Explanation: b[] occurs as a subarray in a[] from index 3 to 3 and from index 4 to 4.
Table of Content
The idea is to check for all possible indices in a[] as starting index of subarray b[]. For each index, compare the subarray of a[] with b[] using a nested loop. If all the elements match, store the starting index in result. If any element does not match, break and check for next starting index.
Consider the following dry run: a = [2, 4, 1, 0, 4, 1, 1], b = [4, 1]
Final answer: [1, 4]
1 4
The idea is to use the KMP algorithm by treating array
aas the text and arraybas the pattern. Instead of characters, we compare integers. We first build the LPS (Longest Prefix Suffix) array for the pattern, which helps us skip unnecessary comparisons when a mismatch occurs. Then, while scanning the text, we use this LPS information to efficiently find all occurrences of the pattern in O(n + m) time.
Consider this dry run for better understanding: a = [2, 4, 1, 0, 4, 1, 1], b = [4, 1]
Final answer: [1, 4]
1 4
Related Topic: Subarrays, Subsequences, and Subsets in Array