Check if the rows of a binary matrix can be made unique by removing a single column
Given a binary matrix mat[][] of size M * N. The task is to check whether the row of the matrix will be unique after deleting a column from the matrix.
Example:
Input: mat[][] = {
{1 0 1},
{0 0 0},
{1 0 0}
}
Output: Yes
After deleting 2nd column each row of matrix become unique.
Input:mat[][] = {
{1 0},
{1 0}
}
Output: No
Approach:
- Take matrix as an array of string and each row consider as single string.
- Initialise a variable count = 0 to count duplicate rows in matrix.
- Now take two nested loop outer loop from i = 0 to str.length() and inner loop from j = 0 to i and for each index check if str[i] == str[j] then increment count by 1 and break the loop.
- Now check if count>= 1 then print No else print Yes.
Below is implementation of Above Approach:
C++
#include <bits/stdc++.h>
using namespace std;
int uniqueRows(string s[], int m, int n)
{
int i, j, count = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < i; j++) {
if (s[i] == s[j]) {
count++;
break ;
}
}
}
if (count >= 1) {
cout << "No" << endl;
}
else {
cout << "Yes" << endl;
}
return 0;
}
int main()
{
int m = 3, n = 3;
string s[] = {
{ 1, 0, 1 },
{ 0, 0, 0 },
{ 1, 0, 0 }
};
uniqueRows(s, m, n);
return 0;
}
|
Java
class GFG
{
static int uniqueRows( int [][]s,
int m, int n)
{
int i, j, count = 0 ;
for (i = 0 ; i < n; i++)
{
for (j = 0 ; j < i; j++)
{
if (s[i] == s[j])
{
count++;
break ;
}
}
}
if (count >= 1 )
System.out.println( "No" );
else
System.out.println( "Yes" );
return 0 ;
}
public static void main(String[] args)
{
int m = 3 , n = 3 ;
int s[][] = { { 1 , 0 , 1 },
{ 0 , 0 , 0 },
{ 1 , 0 , 0 } };
uniqueRows(s, m, n);
}
}
|
Python3
def uniqueRows(s, m, n):
i, j, count = 0 , 0 , 0
for i in range (n):
for j in range (i):
if (s[i] = = s[j]):
count + = 1
break
if (count > = 1 ):
print ( "No" )
else :
print ( "Yes" )
m = 3
n = 3
s = [[ 1 , 0 , 1 ],
[ 0 , 0 , 0 ],
[ 1 , 0 , 0 ]]
uniqueRows(s, m, n)
|
C#
using System;
class GFG
{
static int uniqueRows( string []s,
int m, int n)
{
int i, j, count = 0;
for (i = 0; i < n; i++)
{
for (j = 0; j < i; j++)
{
if (s[i] == s[j])
{
count++;
break ;
}
}
}
if (count >= 1)
Console.WriteLine( "No" );
else
Console.WriteLine( "Yes" );
return 0;
}
public static void Main(String[] args)
{
int m = 3, n = 3;
string []s = { "101" , "000" , "100" };
uniqueRows(s, m, n);
}
}
|
Javascript
<script>
function uniqueRows(s, m, n)
{
var i, j, count = 0;
for (i = 0; i < n; i++)
{
for (j = 0; j < i; j++)
{
if (s[i] == s[j])
{
count++;
break ;
}
}
}
if (count >= 1)
{
document.write( "No" );
}
else
{
document.write( "Yes" );
}
}
var m = 3, n = 3;
var s = [ [ 1, 0, 1 ],
[ 0, 0, 0 ],
[ 1, 0, 0 ] ];
uniqueRows(s, m, n);
</script>
|
Time Complexity : O(n2) ,where n is number of rows of given matrix.
Space Complexity : O(1) ,as we are not using any extra space.
Last Updated :
21 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...