Subarray of length K whose concatenation forms a palindrome | Java program for the above approach ; Function to check if a number is Palindrome or not here i is the starting index and j is the last index of the subarray ; If the integer at i is not equal to j then the subarray is not palindrome ; Otherwise ; all a [ i ] is equal to a [ j ] then the subarray is palindrome ; Function to find a subarray whose concatenation forms a palindrome and return its starting index ; Iterating over subarray of length k and checking if that subarray is palindrome ; If no subarray is palindrome ; Driver code
import java . io . * ; class GFG { public static boolean palindrome ( int [ ] a , int i , int j ) { while ( i < j ) { if ( a [ i ] != a [ j ] ) return false ; i ++ ; j -- ; } return true ; } static int findSubArray ( int [ ] arr , int k ) { int n = arr . length ; for ( int i = 0 ; i <= n - k ; i ++ ) { if ( palindrome ( arr , i , i + k - 1 ) ) return i ; } return - 1 ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 5 , 1 , 3 } ; int k = 4 ; int ans = findSubArray ( arr , k ) ; if ( ans == - 1 ) System . out . print ( - 1 + "NEW_LINE"); else { for ( int i = ans ; i < ans + k ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . print ( "NEW_LINE"); } } }