Rearrange array to make Bitwise XOR of similar indexed elements of two arrays is same | Java program for the above approach ; Function to rearrange the array B [ ] such that A [ i ] ^ B [ i ] is same for each element ; Store frequency of elements ; Stores xor value ; Taking xor of all the values of both arrays ; Store frequency of B [ ] ; Find the array B [ ] after rearrangement ; If the updated value is present then decrement its frequency ; Otherwise return empty vector ; Utility function to rearrange the array B [ ] such that A [ i ] ^ B [ i ] is same for each element ; Store rearranged array B ; If rearrangement possible ; Otherwise return - 1 ; Driver Code ; Given vector A ; Given vector B ; Size of the vector ; Function Call
import java . io . * ; import java . util . * ; class GFG { static ArrayList < Integer > rearrangeArray ( ArrayList < Integer > A , ArrayList < Integer > B , int N ) { HashMap < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; int xor_value = 0 ; for ( int i = 0 ; i < N ; i ++ ) { xor_value ^= A . get ( i ) ; xor_value ^= B . get ( i ) ; m . put ( B . get ( i ) , m . getOrDefault ( B . get ( i ) + 1 , 0 ) ) ; } for ( int i = 0 ; i < N ; i ++ ) { B . set ( i , A . get ( i ) ^ xor_value ) ; if ( m . getOrDefault ( B . get ( i ) , - 1 ) != - 1 ) { m . put ( B . get ( i ) , m . getOrDefault ( B . get ( i ) , 0 ) - 1 ) ; } else return ( new ArrayList < Integer > ( ) ) ; } return B ; } static void rearrangeArrayUtil ( ArrayList < Integer > A , ArrayList < Integer > B , int N ) { ArrayList < Integer > ans = rearrangeArray ( A , B , N ) ; if ( ans . size ( ) != 0 ) { for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { System . out . print ( ans . get ( i ) + " ▁ " ) ; } } else { System . out . println ( " - 1" ) ; } } public static void main ( String [ ] args ) { ArrayList < Integer > A = new ArrayList < Integer > ( Arrays . asList ( 13 , 21 , 33 , 49 , 53 ) ) ; ArrayList < Integer > B = new ArrayList < Integer > ( Arrays . asList ( 54 , 50 , 34 , 22 , 14 ) ) ; int N = ( int ) A . size ( ) ; rearrangeArrayUtil ( A , B , N ) ; } }