Rearrange an array to make similar indexed elements different from that of another array | Java program for the above approach ; Function to find the arrangement of array B [ ] such that element at each index of A [ ] and B [ ] are not equal ; Length of array ; Print not possible , if arrays only have single equal element ; Reverse array B ; Traverse over arrays to check if there is any index where A [ i ] and B [ i ] are equal ; Swap B [ i ] with B [ i - 1 ] ; Break the loop ; Print required arrangement of array B ; Driver Code ; Given arrays A [ ] and B [ ] ; Function Call
import java . util . * ; import java . lang . * ; class GFG { static void RearrangeB ( int [ ] A , int [ ] B ) { int n = A . length ; if ( n == 1 && A [ 0 ] == B [ 0 ] ) { System . out . println ( " - 1" ) ; return ; } for ( int i = 0 ; i < n / 2 ; i ++ ) { int t = B [ i ] ; B [ i ] = B [ n - i - 1 ] ; B [ n - i - 1 ] = t ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( B [ i ] == A [ i ] ) { int t = B [ i + 1 ] ; B [ i + 1 ] = B [ i ] ; B [ i ] = t ; break ; } } for ( int k : B ) System . out . print ( k + " ▁ " ) ; } public static void main ( String [ ] args ) { int [ ] A = { 2 , 4 , 5 , 8 } ; int [ ] B = { 2 , 4 , 5 , 8 } ; RearrangeB ( A , B ) ; } }