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

C++Server Side ProgrammingProgramming

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[0]) {
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[0]);
int m = sizeof(B)/sizeof(B[0]);
cout << "Minimum length of subarray: " << lengthMinSubarray(A, n, B, m);
}

## Output

Minimum length of subarray: 3
Published on 19-Dec-2019 12:03:56