Smallest subarray which upon repetition gives the original array | C ++ program for the above approach ; Function to print the array ; Function to find the smallest subarray ; Corner Case ; Initialize the auxiliary subarray ; Push the first 2 elements into the subarray brr [ ] ; Iterate over the length of subarray ; If array can be divided into subarray of i equal length ; Check if on repeating the current subarray gives the original array or not ; Subarray found ; Add current element into subarray ; No subarray found ; Driver Code ; Function call
#include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; void printArray ( vector < int > & brr ) { for ( auto & it : brr ) { cout << it << ' ▁ ' ; } } void RepeatingSubarray ( int arr [ ] , int N ) { if ( N < 2 ) { cout << " - 1" ; } vector < int > brr ; brr . push_back ( arr [ 0 ] ) ; brr . push_back ( arr [ 1 ] ) ; for ( int i = 2 ; i < N / 2 + 1 ; i ++ ) { if ( N % i == 0 ) { bool a = false ; int n = brr . size ( ) ; int j = i ; while ( j < N ) { int K = j % i ; if ( arr [ j ] == brr [ K ] ) { j ++ ; } else { a = true ; break ; } } if ( ! a && j == N ) { printArray ( brr ) ; return ; } } brr . push_back ( arr [ i ] ) ; } cout << " - 1" ; return ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 1 , 2 , 2 , 1 , 2 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; RepeatingSubarray ( arr , N ) ; return 0 ; }