VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-whether-an-array-is-subarray-of-another-array/

⇱ All Occurrences of Subarray in Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

All Occurrences of Subarray in Array

Last Updated : 5 May, 2026

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.

[Naive Approach] Comparing All Subarrays - O(n * m) Time and O(1) Space

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]

  • For i = 0 --> (2 ≠ 4) --> mismatch --> move to next i
  • For i = 1 --> (4 = 4, 1 = 1) --> match --> add index 1
  • For i = 2 --> (1 ≠ 4) --> mismatch --> move to next i
  • For i = 3 --> (0 ≠ 4) --> mismatch --> move to next i
  • For i = 4 --> (4 = 4, 1 = 1) --> match --> add index 4
  • For i = 5 --> (1 ≠ 4) --> mismatch --> move to next i

Final answer: [1, 4]


Output
1 4 

[Expected Approach] Using KMP Algorithm - O(m + n) Time and O(m) Space

The idea is to use the KMP algorithm by treating array a as the text and array b as 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]

  • Step 0: Build LPS for b --> b = [4, 1] --> lps = [0, 0]
  • Step 1: KMP Algorithm
    For i = 0, j = 0 --> 2 ≠ 4 --> j = 0, i++
    For i = 1, j = 0 --> 4 = 4 --> i = 2, j = 1
    For i = 2, j = 1 --> 1 = 1 --> match --> add (2 - 2 = 1) --> j = 0
    For i = 2, j = 0 --> 1 ≠ 4 --> i++
    For i = 3, j = 0 --> 0 ≠ 4 --> i++
    For i = 4, j = 0 --> 4 = 4 --> i = 5, j = 1
    For i = 5, j = 1 --> 1 = 1 --> match --> add (5 - 2 = 4) --> j = 0
    For i = 5, j = 0 --> 1 ≠ 4 --> i++
    For i = 6, j = 0 --> 1 ≠ 4 --> i++

Final answer: [1, 4]


Output
1 4 

Related Topic: Subarrays, Subsequences, and Subsets in Array

Comment
Article Tags:
Article Tags: