Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Algorithms
  • Analysis of Algorithms
  • Sorting
  • Searching
  • Greedy
  • Recursion
  • Backtracking
  • Dynamic Programming
  • Divide and Conquer
  • Geometric Algorithms
  • Mathematical Algorithms
  • Pattern Searching
  • Bitwise Algorithms
  • Branch & Bound
  • Randomized Algorithms
Open In App
Next Article:
Product of all Subarrays of an Array
Next article icon

Find All Occurrences of Subarray in Array

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given two arrays a[] and b[], the task is to find all starting indices of b[] as a subarray in a[].

Examples: 

Input: a[] = [2, 3, 0, 3, 0, 3, 0], b[] = [3, 0, 3, 0] 
Output: [1, 3]
Explanation: The subarray a[1…4] = b[] and subarray a[3…6] = b[].

Input : a[] = [1, 2, 3, 4, 5], b[] = [2, 5, 6]
Output: []
Explanation: No subarray of a[] matches with b[].

Table of Content

  • [Naive Approach] Comparing All Subarrays – O(n*m) Time and O(1) Space
  • [Expected Approach] Using KMP Algorithm – O(n+m) Time and O(m) Space

[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.

C++
// C++ Program to search for subarray by matching  // with every possible subarray  #include <iostream> #include <vector> using namespace std;  vector<int> search(vector<int> &a, vector<int> &b) {     int n = a.size(), m = b.size();     vector<int> res;        // Iterate over all possible starting indices 	for(int i = 0; i < n - m + 1; i++) {         bool isSame = true;     	for(int j = 0; j < m; j++) {                        // If any character does not match, break             // and begin from the next starting index         	if(a[i + j] != b[j]) {             	isSame = false;                 break;             }         }                // If all characters are matched, store the         // starting index         if(isSame)             res.push_back(i);     }     return res; }  int main() { 	vector<int> a = {2, 3, 0, 3, 0, 3, 0};     vector<int> b = {3, 0, 3, 0};        vector<int> res = search(a, b);     for(int idx: res)         cout << idx << " "; } 
Java
// Java Program to search for subarray by matching  // with every possible subarray  import java.util.ArrayList; import java.util.List;  class GfG {     static List<Integer> search(int[] a, int[] b) {         int n = a.length, m = b.length;         List<Integer> res = new ArrayList<>();                  // Iterate over all possible starting indices         for (int i = 0; i < n - m + 1; i++) {             boolean isSame = true;                          // If any character does not match, break             // and begin from the next starting index             for (int j = 0; j < m; j++) {                 if (a[i + j] != b[j]) {                     isSame = false;                     break;                 }             }                          // If all characters are matched, store              // the starting index             if (isSame)                 res.add(i);         }         return res;     }      public static void main(String[] args) {         int[] a = {2, 3, 0, 3, 0, 3, 0};         int[] b = {3, 0, 3, 0};          List<Integer> res = search(a, b);         for (int idx : res)             System.out.print(idx + " ");     } } 
Python
# Python Program to search for subarray by matching  # with every possible subarray  def search(a, b):     n = len(a)     m = len(b)     res = []        # Iterate over all possible starting indices     for i in range(n - m + 1):         isSame = True         for j in range(m):                        # If any character does not match, break             # and begin from the next starting index             if a[i + j] != b[j]:                 isSame = False                 break                  # If all characters are matched, store the starting index         if isSame:             res.append(i)          return res  if __name__ == "__main__":     a = [2, 3, 0, 3, 0, 3, 0]     b = [3, 0, 3, 0]      res = search(a, b)     for idx in res:         print(idx, end=" ") 
C#
// C# Program to search for subarray by matching  // with every possible subarray  using System; using System.Collections.Generic;  class GfG {     static List<int> Search(int[] a, int[] b) {         int n = a.Length, m = b.Length;         List<int> res = new List<int>();            // Iterate over all possible starting indices         for (int i = 0; i < n - m + 1; i++) {             bool isSame = true;             for (int j = 0; j < m; j++) {                                // If any character does not match, break                 // and begin from the next starting index                 if (a[i + j] != b[j]) {                     isSame = false;                     break;                 }             }                        // If all characters are matched, store the starting index             if (isSame)                 res.Add(i);         }         return res;       }      static void Main() {         int[] a = { 2, 3, 0, 3, 0, 3, 0 };         int[] b = { 3, 0, 3, 0 };            List<int> res = Search(a, b);         foreach (int idx in res) {             Console.Write(idx + " ");         }     } } 
JavaScript
// JavaScript Program to search for subarray by matching  // with every possible subarray  function search(a, b) {     let n = a.length, m = b.length;     let res = [];        // Iterate over all possible starting indices     for (let i = 0; i < n - m + 1; i++) {         let isSame = true;         for (let j = 0; j < m; j++) {                        // If any character does not match, break             // and begin from the next starting index             if (a[i + j] !== b[j]) {                 isSame = false;                 break;             }         }                // If all characters are matched, store the starting index         if (isSame)             res.push(i);     }     return res; }  // Driver code let a = [2, 3, 0, 3, 0, 3, 0]; let b = [3, 0, 3, 0];  let res = search(a, b); for (let idx of res) {     console.log(idx + " "); } 

Output
1 3 

Time Complexity: O(n*m), where n and m are the sizes of the arrays a[] and b[], respectively. 
Space Complexity: O(1) as we are not using any additional space to store the arrays or any other variables.

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

The idea is to use KMP Algorithm with a[] as the text and b[] as the pattern. So, instead of comparing characters, we can compare numbers of the array to construct the lps[] array and find all occurrences of b[] in a[].

C++
// C++ Program to search for subarray using KMP Algorithm  #include <iostream> #include <vector> using namespace std;  void constructLps(vector<int> &pat, vector<int> &lps) {      // len stores the length of longest prefix which     // is also a suffix for the previous index     int len = 0;      // lps[0] is always 0     lps[0] = 0;      int i = 1;     while (i < pat.size()) {          // If numbers match, increment the size of lps         if (pat[i] == pat[len]) {             len++;             lps[i] = len;             i++;         }          // If there is a mismatch         else {             if (len != 0) {                  // Update len to the previous lps value                 // to avoid reduntant comparisons                 len = lps[len - 1];             }             else {                  // If no matching prefix found, set lps[i] to 0                 lps[i] = 0;                 i++;             }         }     } }  vector<int> search(vector<int> &a, vector<int> &b) {     int n = a.size();     int m = b.size();      vector<int> lps(m);     vector<int> res;      constructLps(b, lps);      // Pointers i and j, for traversing a[] and b[]     int i = 0;     int j = 0;      while (i < n) {          // If elements match, move both pointers forward         if (a[i] == b[j]) {             i++;             j++;              // If all elements of b[] are matched              // store the start index in result             if (j == m) {                 res.push_back(i - j);                  // Use LPS of previous index to                 // skip unnecessary comparisons                 j = lps[j - 1];             }         }          // If there is a mismatch         else {              // Use lps value of previous index             // to avoid redundant comparisons             if (j != 0)                 j = lps[j - 1];             else                 i++;         }     }     return res; }  int main() { 	vector<int> a = {2, 3, 0, 3, 0, 3, 0};     vector<int> b = {3, 0, 3, 0};        vector<int> res = search(a, b);     for(int idx: res)         cout << idx << " "; } 
Java
// Java Program to search for subarray using KMP Algorithm  import java.util.ArrayList; import java.util.List;  class GfG {          // Function to construct LPS array     static void constructLps(int[] pat, int[] lps) {          // len stores the length of longest prefix which         // is also a suffix for the previous index         int len = 0;          // lps[0] is always 0         lps[0] = 0;          int i = 1;         while (i < pat.length) {              // If numbers match, increment the size of lps             if (pat[i] == pat[len]) {                 len++;                 lps[i] = len;                 i++;             }              // If there is a mismatch             else {                 if (len != 0) {                      // Update len to the previous lps value                     // to avoid redundant comparisons                     len = lps[len - 1];                 } else {                      // If no matching prefix found, set lps[i] to 0                     lps[i] = 0;                     i++;                 }             }         }     }      // Function to search for the subarray using KMP algorithm     static List<Integer> search(int[] a, int[] b) {         int n = a.length;         int m = b.length;          int[] lps = new int[m];         List<Integer> res = new ArrayList<>();          constructLps(b, lps);          // Pointers i and j, for traversing a[] and b[]         int i = 0;         int j = 0;          while (i < n) {              // If elements match, move both pointers forward             if (a[i] == b[j]) {                 i++;                 j++;                  // If all elements of b[] are matched                  // store the start index in result                 if (j == m) {                     res.add(i - j);                      // Use LPS of previous index to                     // skip unnecessary comparisons                     j = lps[j - 1];                 }             }              // If there is a mismatch             else {                  // Use lps value of previous index                 // to avoid redundant comparisons                 if (j != 0)                     j = lps[j - 1];                 else                     i++;             }         }         return res;     }      public static void main(String[] args) {         int[] a = {2, 3, 0, 3, 0, 3, 0};         int[] b = {3, 0, 3, 0};            List<Integer> res = search(a, b);         for (int idx : res)             System.out.print(idx + " ");     } } 
Python
# Python Program to search for subarray using KMP Algorithm  def constructLps(pat, lps):     # len stores the length of longest prefix which     # is also a suffix for the previous index     length = 0      # lps[0] is always 0     lps[0] = 0      i = 1     while i < len(pat):          # If numbers match, increment the size of lps         if pat[i] == pat[length]:             length += 1             lps[i] = length             i += 1          # If there is a mismatch         else:             if length != 0:                  # Update length to the previous lps value                 # to avoid redundant comparisons                 length = lps[length - 1]             else:                  # If no matching prefix found, set lps[i] to 0                 lps[i] = 0                 i += 1  def search(a, b):     n = len(a)     m = len(b)      lps = [0] * m     res = []      constructLps(b, lps)      # Pointers i and j, for traversing a[] and b[]     i = 0     j = 0      while i < n:          # If elements match, move both pointers forward         if a[i] == b[j]:             i += 1             j += 1              # If all elements of b[] are matched              # store the start index in result             if j == m:                 res.append(i - j)                  # Use LPS of previous index to                 # skip unnecessary comparisons                 j = lps[j - 1]         else:              # If there is a mismatch             # Use lps value of previous index             # to avoid redundant comparisons             if j != 0:                 j = lps[j - 1]             else:                 i += 1      return res  if __name__ == "__main__":     a = [2, 3, 0, 3, 0, 3, 0]     b = [3, 0, 3, 0]      res = search(a, b)     for idx in res:         print(idx, end=" ") 
C#
// C# Program to search for subarray using KMP Algorithm  using System; using System.Collections.Generic;  class GfG {     // Function to construct the LPS array (Longest Prefix Suffix)     static void ConstructLps(int[] pat, int[] lps) {         // len stores the length of the longest prefix which         // is also a suffix for the previous index         int len = 0;          // lps[0] is always 0         lps[0] = 0;          int i = 1;         while (i < pat.Length) {             // If numbers match, increment the size of lps             if (pat[i] == pat[len]) {                 len++;                 lps[i] = len;                 i++;             }             // If there is a mismatch             else {                 if (len != 0) {                     // Update len to the previous lps value                     // to avoid redundant comparisons                     len = lps[len - 1];                 }                 else {                     // If no matching prefix found, set lps[i] to 0                     lps[i] = 0;                     i++;                 }             }         }     }      // Function to search for the subarray     static List<int> Search(int[] a, int[] b) {         int n = a.Length;         int m = b.Length;          int[] lps = new int[m];         List<int> res = new List<int>();          ConstructLps(b, lps);          // Pointers i and j, for traversing a[] and b[]         int i = 0;         int j = 0;          while (i < n) {             // If elements match, move both pointers forward             if (a[i] == b[j]) {                 i++;                 j++;                  // If all elements of b[] are matched                  // store the start index in result                 if (j == m) {                     res.Add(i - j);                      // Use LPS of previous index to                     // skip unnecessary comparisons                     j = lps[j - 1];                 }             }             // If there is a mismatch             else {                 // Use lps value of previous index                 // to avoid redundant comparisons                 if (j != 0)                     j = lps[j - 1];                 else                     i++;             }         }          // Convert the List<int> to an int[] before returning         return res;     }      static void Main() {         int[] a = { 2, 3, 0, 3, 0, 3, 0 };         int[] b = { 3, 0, 3, 0 };          List<int> res = Search(a, b);         foreach (int idx in res) {             Console.Write(idx + " ");         }     } } 
JavaScript
// JavaScript Program to search for subarray using KMP Algorithm  function constructLps(pat, lps) {      // len stores the length of longest prefix which     // is also a suffix for the previous index     let len = 0;      // lps[0] is always 0     lps[0] = 0;      let i = 1;     while (i < pat.length) {          // If numbers match, increment the size of lps         if (pat[i] === pat[len]) {             len++;             lps[i] = len;             i++;         }         // If there is a mismatch         else {             if (len !== 0) {                              // Update len to the previous lps value                 // to avoid redundant comparisons                 len = lps[len - 1];             }             else {                              // If no matching prefix found, set lps[i] to 0                 lps[i] = 0;                 i++;             }         }     } }  function search(a, b) {     let n = a.length;     let m = b.length;      let lps = new Array(m);     let res = [];      constructLps(b, lps);      // Pointers i and j, for traversing a[] and b[]     let i = 0;     let j = 0;      while (i < n) {          // If elements match, move both pointers forward         if (a[i] === b[j]) {             i++;             j++;              // If all elements of b[] are matched              // store the start index in result             if (j === m) {                 res.push(i - j);                  // Use LPS of previous index to                 // skip unnecessary comparisons                 j = lps[j - 1];             }         }         // If there is a mismatch         else {              // Use lps value of previous index             // to avoid redundant comparisons             if (j !== 0)                 j = lps[j - 1];             else                 i++;         }     }      return res; }  // Driver Code let a = [2, 3, 0, 3, 0, 3, 0]; let b = [3, 0, 3, 0];  let res = search(a, b); for (let idx of res) {     console.log(idx + " "); } 

Output
1 3 

Time Complexity: O(n+m), where n and m are the sizes of the arrays a[] and b[], respectively. 
Auxiliary Space: O(m), for lps[] array.

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Product of all Subarrays of an Array

K

Kushdeep_Mittal
Improve
Article Tags :
  • Algorithms
  • DSA
Practice Tags :
  • Algorithms

Similar Reads

  • Remove All Occurrences of an Element in an Array
    Given an integer array arr[] and an integer ele the task is to the remove all occurrences of ele from arr[] in-place and return the number of elements which are not equal to ele. If there are k number of elements which are not equal to ele then the input array arr[] should be modified such that the
    6 min read
  • Find the Kth occurrence of an element in a sorted Array
    Given a sorted array arr[] of size N, an integer X, and a positive integer K, the task is to find the index of Kth occurrence of X in the given array. Examples: Input: N = 10, arr[] = [1, 2, 3, 3, 4, 5, 5, 5, 5, 5], X = 5, K = 2Output: Starting index of the array is '0' Second occurrence of 5 is at
    15+ min read
  • Count Subarrays of 1 in Binary Array
    Given an array arr[] of size N, the array contains only 1s and 0s, and the task is to return the count of the total number of subarrays where all the elements of the subarrays are 1. Examples: Input: N = 4, arr[] = {1, 1, 1, 0}Output: 6Explanation: Subarrays of 1 will look like the following: [1], [
    13 min read
  • Product of all Subarrays of an Array
    Given an array of integers arr of size N, the task is to print products of all subarrays of the array. Examples: Input: arr[] = {2, 4} Output: 64 Here, subarrays are [2], [2, 4], [4] Products are 2, 8, 4 Product of all Subarrays = 64 Input : arr[] = {10, 3, 7} Output : 27783000 Here, subarrays are [
    7 min read
  • Product of all Subarrays of an Array | Set 2
    Given an array arr[] of integers of size N, the task is to find the products of all subarrays of the array.Examples: Input: arr[] = {2, 4} Output: 64 Explanation: Here, subarrays are {2}, {2, 4}, and {4}. Products of each subarray are 2, 8, 4. Product of all Subarrays = 64Input: arr[] = {1, 2, 3} Ou
    5 min read
  • Count number of occurrences (or frequency) in a sorted array
    Given a sorted array arr[] and an integer target, the task is to find the number of occurrences of target in given array. Examples: Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 2Output: 4Explanation: 2 occurs 4 times in the given array. Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 4Output: 0Expl
    9 min read
  • Count of Subarrays not containing all elements of another Array
    Given two arrays nums[] of size N and target[]. The task is to find the number of non-empty subarrays of nums[] that do not contain every number in the target[]. As the answer can be very large, calculate the result modulo 109+7. Examples: Input: nums = {1, 2, 2}, target = {1, 2}Output: 4Explanation
    12 min read
  • Smallest subarray with all occurrences of a most frequent element
    Given an array, A. Let x be an element in the array. x has the maximum frequency in the array. Find the smallest subsegment of the array which also has x as the maximum frequency element. Examples: Input : arr[] = {4, 1, 1, 2, 2, 1, 3, 3} Output : 1, 1, 2, 2, 1 The most frequent element is 1. The sm
    8 min read
  • Find sum of count of duplicate numbers in all subarrays of given array
    Given an array arr[] of size N. The task it to find the sum of count of duplicate numbers in all subarrays of given array arr[]. For example array {1, 2, 3, 2, 3, 2} has two duplicate elements (i.e, 2 and 3 come more than one time in the array). Examples:Input: N = 2, arr = {3,3}Output: 1Explanation
    6 min read
  • Product of all non repeating Subarrays of an Array
    Given an array containing distinct integers arr[] of size N, the task is to print the product of all non-repeating subarrays of the array. Examples: Input: arr[] = {2, 4} Output: 64 Explanation: The possible subarrays for the given array are {2}, {2, 4}, {4} The products are 2, 8, 4 respectively. Th
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences