Construct binary palindrome by repeated appending and trimming | JAVA code to form binary palindrome ; function to apply DFS ; set the parent marked ; if the node has not been visited set it and its children marked ; link which digits must be equal ; connect the two indices ; set everything connected to first character as 1 ; Driver code
import java . util . * ; class GFG { static void dfs ( int parent , int ans [ ] , Vector < Integer > connectchars [ ] ) { ans [ parent ] = 1 ; for ( int i = 0 ; i < connectchars [ parent ] . size ( ) ; i ++ ) { if ( ans [ connectchars [ parent ] . get ( i ) ] != 1 ) dfs ( connectchars [ parent ] . get ( i ) , ans , connectchars ) ; } } static void printBinaryPalindrome ( int n , int k ) { int [ ] arr = new int [ n ] ; int [ ] ans = new int [ n ] ; Vector < Integer > [ ] connectchars = new Vector [ k ] ; for ( int i = 0 ; i < k ; i ++ ) connectchars [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = i % k ; for ( int i = 0 ; i < n / 2 ; i ++ ) { connectchars [ arr [ i ] ] . add ( arr [ n - i - 1 ] ) ; connectchars [ arr [ n - i - 1 ] ] . add ( arr [ i ] ) ; } dfs ( 0 , ans , connectchars ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( ans [ arr [ i ] ] ) ; } public static void main ( String [ ] args ) { int n = 10 , k = 4 ; printBinaryPalindrome ( n , k ) ; } }