# Find smallest subarray that contains all elements in same order in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have two arrays of size m and n, The task is to find minimum length subarray in the first array, that contains all the elements if the second array. Element in second array may be present in the large array in non-contiguous but order must be same. So if two arrays are like A = [2, 2, 4, 5, 8, 9], and B = [2, 5, 9], then the output will be 5. As the smallest subarray of A, will be [2, 4, 5, 8, 9]. Here all elements like [2, 5, 9] are in the same order. So the size is 5.

We can solve this by checking the first element match with the first element of second array. When the first element matches, then we match the rest of the elements of the second array in the main array, when all elements match, then update the length if needed. After doing this return the minimum length of subarray.

## Example

#include<iostream>
using namespace std;
int lengthMinSubarray(int A[], int n, int B[], int m) {
int res = INT_MAX;
for (int i = 0; i < n - m + 1; i++) {
if (A[i] == B) {
int j = 0, idx = i;
for (; idx < n; idx++) {
if (A[idx] == B[j])
j++;
if (j == m)
break;
}
if (j == m && res > idx - i + 1)
res = (idx == n) ? idx - i : idx - i + 1;
}
}
return res;
}
int main() {
int A[] = { 5, 6, 5, 2, 7, 5, 6, 7, 5, 5, 7 };
int B[] = { 5, 5, 7 };
int n = sizeof(A)/sizeof(A);
int m = sizeof(B)/sizeof(B);
cout << "Minimum length of subarray: " << lengthMinSubarray(A, n, B, m);
}

## Output

Minimum length of subarray: 3