Smallest subarray which upon repetition gives the original array | Java 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
import java . util . * ; class GFG { static void printArray ( Vector < Integer > brr ) { for ( int it : brr ) { System . out . print ( it + " ▁ " ) ; } } static void RepeatingSubarray ( int arr [ ] , int N ) { if ( N < 2 ) { System . out . print ( " - 1" ) ; } Vector < Integer > brr = new Vector < Integer > ( ) ; brr . add ( arr [ 0 ] ) ; brr . add ( arr [ 1 ] ) ; for ( int i = 2 ; i < N / 2 + 1 ; i ++ ) { if ( N % i == 0 ) { boolean a = false ; int n = brr . size ( ) ; int j = i ; while ( j < N ) { int K = j % i ; if ( arr [ j ] == brr . get ( K ) ) { j ++ ; } else { a = true ; break ; } } if ( ! a && j == N ) { printArray ( brr ) ; return ; } } brr . add ( arr [ i ] ) ; } System . out . print ( " - 1" ) ; return ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 2 , 1 , 2 , 2 , 1 , 2 , 2 } ; int N = arr . length ; RepeatingSubarray ( arr , N ) ; } }