Sunday, June 2, 2019

Flip Columns For Maximum Number of Equal Rows


Given a matrix consisting of 0s and 1s, we may choose any number of columns in the
matrix and flip every cell in that column. Flipping a cell changes the value of that cell
from 0 to 1 or from 1 to 0.
Return the maximum number of rows that have all values equal after some
number of flips.

Example 1:
Input: [[0,1],[1,1]]
Output: 1 Explanation: After flipping no values, 1 row has all
values equal.
Example 2:
Input: [[0,1],[1,0]]
Output: 2 Explanation: After flipping values in the first column, both rows
have equal values.

Example 3:

Input: [[0,0,0],[0,0,1],[1,1,0]]
Output: 2 Explanation: After flipping values in the first two columns, the last two rows
have equal values.
Note:
1 <= matrix.length <= 300
1 <= matrix[i].length <= 300
All matrix[i].length's are equal
matrix[i][j] is 0 or 1.


Solution:

Understanding the problem-

We need to flip columns such that all values in a row are equal. i.e. all 0s or all 1s
Any Row can have all values equal after some number of flips.
eg:
[0,0,1,0,0,0,1,0] can be [0,0,0,0,0,0,0,0] after flipping 3rd and 7th columns
or
[0,0,1,0,0,0,1,0] can be [1,1,1,1,1,1,1,1] after flipping all columns except 3rd and 7th.
So, in this question if we find the rows that are equal, i.e. row[i]==row[j] where i!=j,
0<=i<=rowsize, 0<=j<=rowsize,
the maximum number of equal rows will give us maximum number of rows that have all
values equal after some flips.

When are rows equal?

Suppose, we have 3 rows r1 = [0,1,0], r2 = [0,1,0] and r3 = [1,0,1]
As we can see, r1 = r2, since all elements in r1 and r2 are same.
What if I say, r1 = r3 in this case?
We can consider r1 = r3 here, since an element can have either 0 or 1 only as its value.
In the above example if we flip all elements of r3, it will be the same as r1.

So flipping the elements in 2nd column in all the rows will result in 3 rows, each having all
their elements equal
[0,0,0], [0,0,0], [1,1,1]

The answer here will be 3.


C++ solution -


No comments:

Post a Comment