Check if rows of a Matrix can be rearranged to make Bitwise XOR of first column non-zero - GeeksforGeeks

23 Apr, 2021
Given a matrix mat[][] of size N * M, the task is to check if it is possible to rearrange the row elements of the matrix such that Bitwise XOR of the first column element is non-zero. If it is possible then print “Yes” else print “No”.
Examples:
Input: mat[][] = {{1, 1, 2}, {2, 2, 2}, {3, 3, 3}}Output: YesExplanation:After rearranging the first row as 2, 1, 1.Bitwise XOR of the first column will be 3 i.e., (2 ^ 2 ^ 3).
Input: mat[][] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}}Output: NoExplanation:As all the rearrangements give same first element so the only combination is (1 ^ 2 ^ 3) which equals zero.Therefore, it is not possible to obtain non-zero Bitwise XOR of the first column.
Approach: Follow the steps below to solve the problem:
Find the Bitwise XOR of the elements of the first column of the matrix and store it in a variable res.
If res is non-zero then print “Yes”.
Else, iterate over all the rows and find the element in a row which is not equal to the element at the first index of this row.
If no such element is present in any row in the above step then print “No” else then print “Yes”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if there is any// row where number of unique elements// are greater than 1string checkRearrangements(    vector<vector<int> > mat, int N, int M){    // Iterate over the matrix    for (int i = 0; i < N; i++) {         for (int j = 1; j < M; j++) {             if (mat[i][0] != mat[i][j]) {                 return "Yes";            }        }    }    return "No";} // Function to check if it is possible// to rearrange mat[][] such that XOR// of its first column is non-zerostring nonZeroXor(vector<vector<int> > mat,                  int N, int M){    int res = 0;     // Find bitwise XOR of the first    // column of mat[][]    for (int i = 0; i < N; i++) {         res = res ^ mat[i][0];    }     // If bitwise XOR of the first    // column of mat[][] is non-zero    if (res != 0)        return "Yes";     // Otherwise check rearrangements    else        return checkRearrangements(mat, N, M);} // Driver Codeint main(){    // Given Matrix mat[][]    vector<vector<int> > mat        = { { 1, 1, 2 },            { 2, 2, 2 },            { 3, 3, 3 } };     int N = mat.size();    int M = mat[0].size();     // Function Call    cout << nonZeroXor(mat, N, M);     return 0;}
// Java program for the// above approachimport java.util.*;class GFG{ // Function to check if there is any// row where number of unique elements// are greater than 1static String checkRearrangements(int[][] mat,                                  int N, int M){  // Iterate over the matrix  for (int i = 0; i < N; i++)  {    for (int j = 1; j < M; j++)    {      if (mat[i][0] != mat[i][j])      {        return "Yes";      }    }  }  return "No";} // Function to check if it is possible// to rearrange mat[][] such that XOR// of its first column is non-zerostatic String nonZeroXor(int[][] mat,                         int N, int M){  int res = 0;   // Find bitwise XOR of the  // first column of mat[][]  for (int i = 0; i < N; i++)  {    res = res ^ mat[i][0];  }   // If bitwise XOR of the first  // column of mat[][] is non-zero  if (res != 0)    return "Yes";   // Otherwise check  // rearrangements  else    return checkRearrangements(mat,                               N, M);} // Driver Codepublic static void main(String[] args){  // Given Matrix mat[][]  int[][] mat = {{1, 1, 2},                 {2, 2, 2},                 {3, 3, 3}};   int N = mat.length;  int M = mat[0].length;   // Function Call  System.out.print(nonZeroXor(mat,                              N, M));}} // This code is contributed by gauravrajput1
# Python3 program for the above approach # Function to check if there is any# row where number of unique elements# are greater than 1def checkRearrangements(mat, N, M):         # Iterate over the matrix    for i in range(N):        for j in range(1, M):            if (mat[i][0] != mat[i][j]):                return "Yes"                     return "No" # Function to check if it is possible# to rearrange mat[][] such that XOR# of its first column is non-zerodef nonZeroXor(mat, N, M):     res = 0     # Find bitwise XOR of the first    # column of mat[][]    for i in range(N):        res = res ^ mat[i][0]     # If bitwise XOR of the first    # column of mat[][] is non-zero    if (res != 0):        return "Yes"     # Otherwise check rearrangements    else:        return checkRearrangements(mat, N, M) # Driver Codeif __name__ == "__main__":     # Given Matrix mat[][]    mat = [ [ 1, 1, 2 ],            [ 2, 2, 2 ],            [ 3, 3, 3 ] ]     N = len(mat)    M = len(mat[0])     # Function Call    print(nonZeroXor(mat, N, M)) # This code is contributed by chitranayal
// C# program for the// above approachusing System; class GFG{ // Function to check if there is any// row where number of unique elements// are greater than 1static String checkRearrangements(int[,] mat,                                  int N, int M){     // Iterate over the matrix  for(int i = 0; i < N; i++)  {    for(int j = 1; j < M; j++)    {      if (mat[i, 0] != mat[i, j])      {        return "Yes";      }    }  }  return "No";} // Function to check if it is possible// to rearrange [,]mat such that XOR// of its first column is non-zerostatic String nonZeroXor(int[,] mat,                         int N, int M){  int res = 0;   // Find bitwise XOR of the  // first column of [,]mat  for(int i = 0; i < N; i++)  {    res = res ^ mat[i, 0];  }   // If bitwise XOR of the first  // column of [,]mat is non-zero  if (res != 0)    return "Yes";   // Otherwise check  // rearrangements  else    return checkRearrangements(mat,                               N, M);} // Driver Codepublic static void Main(String[] args){     // Given Matrix [,]mat  int[,] mat = { { 1, 1, 2 },                 { 2, 2, 2 },                 { 3, 3, 3 } };   int N = mat.GetLength(0);  int M = mat.GetLength(1);   // Function Call  Console.Write(nonZeroXor(mat,                           N, M));}} // This code is contributed by Amit Katiyar
<script> // JavaScript program to implement// the above approach // Function to check if there is any// row where number of unique elements// are greater than 1function checkRearrangements(mat, N, M){  // Iterate over the matrix  for (let i = 0; i < N; i++)  {    for (let j = 1; j < M; j++)    {      if (mat[i][0] != mat[i][j])      {        return "Yes";      }    }  }  return "No";}  // Function to check if it is possible// to rearrange mat[][] such that XOR// of its first column is non-zerofunction nonZeroXor(mat, N, M){  let res = 0;    // Find bitwise XOR of the  // first column of mat[][]  for (let i = 0; i < N; i++)  {    res = res ^ mat[i][0];  }    // If bitwise XOR of the first  // column of mat[][] is non-zero  if (res != 0)    return "Yes";    // Otherwise check  // rearrangements  else    return checkRearrangements(mat,                               N, M);} // Driver Code     // Given Matrix mat[][]  let mat = [[1, 1, 2],             [2, 2, 2],             [3, 3, 3]];    let N = mat.length;  let M = mat[0].length;    // Function Call  document.write(nonZeroXor(mat,                              N, M));           </script>
Yes
 
Time Complexity: O(N * M)Auxiliary Space: O(1)
GauravRajput1
amit143katiyar
ukasp
splevel62
array-rearrange
Bitwise-XOR
Arrays
Bit Magic
Mathematical
Matrix
Arrays
Mathematical
Bit Magic
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Introduction to Arrays
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
Cyclic Redundancy Check and Modulo-2 Division