Check whether an Array is Subarray of another Array - GeeksforGeeks

11 May, 2021
Given two arrays A[] and B[] consisting of and integers. The task is to check whether the array B[] is a subarray of the array A[] or not.Examples:  
Input : A[] = {2, 3, 0, 5, 1, 1, 2}, B[] = {3, 0, 5, 1} Output : YesInput : A[] = {1, 2, 3, 4, 5}, B[] = {2, 5, 6} Output : No  
 
Source : Visa Interview ExperienceSimple Approach: A simple approach is to run two nested loops and generate all subarrays of the array A[] and use one more loop to check if any of the subarray of A[] is equal to the array B[].Efficient Approach : An efficient approach is to use two pointers to traverse both the array simultaneously. Keep the pointer of array B[] still and if any element of A[] matches with the first element of B[] then increase the pointer of both the array else set the pointer of A to the next element of the previous starting point and reset the pointer of B to 0. If all the elements of B are matched then print YES otherwise print NO.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to check if an array is// subarray of another array #include <bits/stdc++.h>using namespace std; // Function to check if an array is// subarray of another arraybool isSubArray(int A[], int B[], int n, int m){    // Two pointers to traverse the arrays    int i = 0, j = 0;     // Traverse both arrays simultaneously    while (i < n && j < m) {         // If element matches        // increment both pointers        if (A[i] == B[j]) {             i++;            j++;             // If array B is completely            // traversed            if (j == m)                return true;        }        // If not,        // increment i and reset j        else {            i = i - j + 1;            j = 0;        }    }     return false;} // Driver Codeint main(){    int A[] = { 2, 3, 0, 5, 1, 1, 2 };    int n = sizeof(A) / sizeof(int);    int B[] = { 3, 0, 5, 1 };    int m = sizeof(B) / sizeof(int);     if (isSubArray(A, B, n, m))        cout << "YES\n";    else        cout << "NO\n";     return 0;}
// Java program to check if an array is// subarray of another arrayclass gfg{         // Function to check if an array is    // subarray of another array    static boolean isSubArray(int A[], int B[],                                   int n, int m)    {        // Two pointers to traverse the arrays        int i = 0, j = 0;             // Traverse both arrays simultaneously        while (i < n && j < m)        {                 // If element matches            // increment both pointers            if (A[i] == B[j])            {                     i++;                j++;                     // If array B is completely                // traversed                if (j == m)                    return true;            }                         // If not,            // increment i and reset j            else            {                i = i - j + 1;                j = 0;            }        }        return false;    }         // Driver Code    public static void main(String arr[])    {        int A[] = { 2, 3, 0, 5, 1, 1, 2 };        int n = A.length;        int B[] = { 3, 0, 5, 1 };        int m = B.length;             if (isSubArray(A, B, n, m))            System.out.println("YES");        else            System.out.println("NO");    }} // This code is contributed by gp6
# Python3 program to check if an array is# subarray of another array # Function to check if an array is# subarray of another arraydef isSubArray(A, B, n, m):         # Two pointers to traverse the arrays    i = 0; j = 0;     # Traverse both arrays simultaneously    while (i < n and j < m):         # If element matches        # increment both pointers        if (A[i] == B[j]):             i += 1;            j += 1;             # If array B is completely            # traversed            if (j == m):                return True;                 # If not,        # increment i and reset j        else:            i = i - j + 1;            j = 0;             return False; # Driver Codeif __name__ == '__main__':    A = [ 2, 3, 0, 5, 1, 1, 2 ];    n = len(A);    B = [ 3, 0, 5, 1 ];    m = len(B);     if (isSubArray(A, B, n, m)):        print("YES");    else:        print("NO"); # This code is contributed by Rajput-Ji
// C# program to check if an array is// subarray of another arrayusing System; public class GFG{          // Function to check if an array is    // subarray of another array    static bool isSubArray(int []A, int []B,                                   int n, int m)    {        // Two pointers to traverse the arrays        int i = 0, j = 0;              // Traverse both arrays simultaneously        while (i < n && j < m)        {                  // If element matches            // increment both pointers            if (A[i] == B[j])            {                      i++;                j++;                      // If array B is completely                // traversed                if (j == m)                    return true;            }                          // If not,            // increment i and reset j            else            {                i = i - j + 1;                j = 0;            }        }        return false;    }          // Driver Code    public static void Main(String []arr)    {        int []A = { 2, 3, 0, 5, 1, 1, 2 };        int n = A.Length;        int []B = { 3, 0, 5, 1 };        int m = B.Length;              if (isSubArray(A, B, n, m))            Console.WriteLine("YES");        else            Console.WriteLine("NO");    }} // This code is contributed by PrinciRaj1992
<script>// Javascript program to check if an array is// subarray of another array  // Function to check if an array is// subarray of another arrayfunction isSubArray(A, B, n,m){    // Two pointers to traverse the arrays    var i = 0, j = 0;     // Traverse both arrays simultaneously    while (i < n && j < m) {         // If element matches        // increment both pointers        if (A[i] == B[j]) {             i++;            j++;             // If array B is completely            // traversed            if (j == m)                return true;        }        // If not,        // increment i and reset j        else {            i = i - j + 1;            j = 0;        }    }     return false;} var A = [ 2, 3, 0, 5, 1, 1, 2 ];var n = A.length;var B = [ 3, 0, 5, 1 ];var m =B.length;if (isSubArray(A, B, n, m))        document.write( "YES<br>");    else        document.write( "NO<br>");         // This code is contributed by SoumikMondal</script>
YES
 
Shashank12
Abhi Reddy
ankthon
Sanjit_Prasad
amyjais35
Mithun Kumar
gp6
princiraj1992
Rajput-Ji
SoumikMondal
Arrays
subarray
Visa
Arrays
Visa
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Linked List vs Array
Search an element in a sorted and rotated array
Queue | Set 1 (Introduction and Array Implementation)
Find the Missing Number
Find Second largest element in an array
Merge two sorted arrays
Chocolate Distribution Problem
Count Inversions in an array | Set 1 (Using Merge Sort)
Program to find largest element in an array