Print unique rows in a given Binary matrix
- Difficulty Level : Hard
- Last Updated : 17 Jun, 2022
Given a binary matrix, print all unique rows of the given matrix.
Example:
Input:
{0, 1, 0, 0, 1}
{1, 0, 1, 1, 0}
{0, 1, 0, 0, 1}
{1, 1, 1, 0, 0}
Output:
0 1 0 0 1
1 0 1 1 0
1 1 1 0 0
Explanation:
The rows are r1={0, 1, 0, 0, 1},
r2={1, 0, 1, 1, 0}, r3={0, 1, 0, 0, 1},
r4={1, 1, 1, 0, 0}, As r1 = r3, remove r3
and print the other rows.
Input:
{0, 1, 0}
{1, 0, 1}
{0, 1, 0}
Output:
0 1 0
1 0 1
Explanation:
The rows are r1={0, 1, 0},
r2={1, 0, 1}, r3={0, 1, 0} As r1 = r3,
remove r3 and print the other rows.Method 1: This method explains the simple approach towards solving the above problem.
Approach: A simple approach would be to check each row with all processed rows. Print the first row. Now, starting from the second row, for each row, compare the row with already processed rows. If the row matches with any of the processed rows, skip it else print it.
Algorithm:
- Traverse the matrix row-wise
- For each row check if there is any similar row less than the current index.
- If any two rows are similar then do not print the row.
- Else print the row.
Implementation:
C++
// Given a binary matrix of M X N of integers,// you need to return only unique rows of binary array#include <bits/stdc++.h>usingnamespacestd;#define ROW 4#define COL 5// The main function that prints// all unique rows in a given matrix.voidfindUniqueRows(intM[ROW][COL]){//Traverse through the matrixfor(inti=0; i<ROW; i++){intflag=0;//check if there is similar column//is already printed, i.e if i and//jth column match.for(intj=0; j<i; j++){flag=1;for(intk=0; k<=COL; k++)if(M[i][k]!=M[j][k])flag=0;if(flag==1)break;}//if no row is similarif(flag==0){//print the rowfor(intj=0; j<COL; j++)cout<<M[i][j]<<" ";cout<<endl;}}}// Driver Codeintmain(){intM[ROW][COL] = {{0, 1, 0, 0, 1},{1, 0, 1, 1, 0},{0, 1, 0, 0, 1},{1, 0, 1, 0, 0}};findUniqueRows(M);return0;}Java
// Given a binary matrix of M X N// of integers, you need to return// only unique rows of binary arrayclassGFG{staticintROW =4;staticintCOL =5;// Function that prints all// unique rows in a given matrix.staticvoidfindUniqueRows(intM[][]){// Traverse through the matrixfor(inti =0; i < ROW; i++){intflag =0;// Check if there is similar column// is already printed, i.e if i and// jth column match.for(intj =0; j < i; j++){flag =1;for(intk =0; k < COL; k++)if(M[i][k] != M[j][k])flag =0;if(flag ==1)break;}// If no row is similarif(flag ==0){// Print the rowfor(intj =0; j < COL; j++)System.out.print(M[i][j] +" ");System.out.println();}}}// Driver Codepublicstaticvoidmain(String[] args){intM[][] = { {0,1,0,0,1},{1,0,1,1,0},{0,1,0,0,1},{1,0,1,0,0} };findUniqueRows(M);}}// This code is contributed by mark_85Python3
# Given a binary matrix of M X N of# integers, you need to return only# unique rows of binary arrayROW=4COL=5# The main function that prints# all unique rows in a given matrix.deffindUniqueRows(M):# Traverse through the matrixforiinrange(ROW):flag=0# Check if there is similar column# is already printed, i.e if i and# jth column match.forjinrange(i):flag=1forkinrange(COL):if(M[i][k] !=M[j][k]):flag=0if(flag==1):break# If no row is similarif(flag==0):# Print the rowforjinrange(COL):(M[i][j], end=" ")()# Driver Codeif__name__=='__main__':M=[ [0,1,0,0,1],[1,0,1,1,0],[0,1,0,0,1],[1,0,1,0,0] ]findUniqueRows(M)# This code is contributed by mohit kumar 29C#
// Given a binary matrix of M X N// of integers, you need to return// only unique rows of binary arrayusingSystem;classGFG{staticintROW = 4;staticintCOL = 5;// Function that prints all// unique rows in a given matrix.staticvoidfindUniqueRows(int[,] M){// Traverse through the matrixfor(inti = 0; i < ROW; i++){intflag = 0;// Check if there is similar column// is already printed, i.e if i and// jth column match.for(intj = 0; j < i; j++){flag = 1;for(intk = 0; k < COL; k++)if(M[i, k] != M[j, k])flag = 0;if(flag == 1)break;}// If no row is similarif(flag == 0){// Print the rowfor(intj = 0; j < COL; j++)Console.Write(M[i, j] +" ");Console.WriteLine();}}}// Driver codestaticvoidMain(){int[,] M = { { 0, 1, 0, 0, 1 },{ 1, 0, 1, 1, 0 },{ 0, 1, 0, 0, 1 },{ 1, 0, 1, 0, 0 } };findUniqueRows(M);}}// This code is contributed by divyeshrabadiya07Javascript
<script>// Given a binary matrix of M X N// of integers, you need to return// only unique rows of binary arraylet ROW = 4;let COL = 5;// Function that prints all// unique rows in a given matrix.functionfindUniqueRows(M){// Traverse through the matrixfor(let i = 0; i < ROW; i++){let flag = 0;// Check if there is similar column// is already printed, i.e if i and// jth column match.for(let j = 0; j < i; j++){flag = 1;for(let k = 0; k < COL; k++)if(M[i][k] != M[j][k])flag = 0;if(flag == 1)break;}// If no row is similarif(flag == 0){// Print the rowfor(let j = 0; j < COL; j++)document.write(M[i][j] +" ");document.write("<br>");}}}// Driver Codelet M = [ [ 0, 1, 0, 0, 1 ],[ 1, 0, 1, 1, 0 ],[ 0, 1, 0, 0, 1 ],[ 1, 0, 1, 0, 0 ] ]findUniqueRows(M)// This code is contributed by unknown2108</script>Output0 1 0 0 1 1 0 1 1 0 1 0 1 0 0Complexity Analysis:
- Time complexity: O( ROW^2 x COL ).
So for every row check if there is any other similar row. So the time complexity is O( ROW^2 x COL ).- Auxiliary Space: O(1).
As no extra space is required.Method 2: This method uses Binary Search Tree to solve the above operation. The Binary Search Tree is a node-based binary tree data structure which has the following properties:
- The left subtree of a node contains only nodes with keys lesser than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
- The left and right subtree each must also be a binary search tree.
- There must be no duplicate nodes.
The above properties of Binary Search Tree provide ordering among keys so that the operations like search, minimum and maximum can be done fast. If there is no order, then we may have to compare every key to search a given key.
Approach: The process must begin from finding the decimal equivalent of each row and inserting them into a BST. As we know, each node of the BST will contain two fields, one field for the decimal value, other for row number. One must not insert a node if it is duplicated. Finally, traverse the BST and print the corresponding rows.
Algorithm:
- Create a BST in which no duplicate elements can be stored. Create a function to convert a row into decimal and to convert the decimal value into binary array.
- Traverse through the matrix and insert the row into the BST.
- Traverse the BST (inorder traversal) and convert the decimal into binary array and print it.
Implementation:
C++14
// Given a binary matrix of M X N of integers,// you need to return only unique rows of binary array#include <bits/stdc++.h>usingnamespacestd;#define ROW 4#define COL 5classBST{intdata;BST *left, *right;public:// Default constructor.BST();// Parameterized constructor.BST(int);// Insert function.BST* Insert(BST *,int);// Inorder traversal.voidInorder(BST *);};//convert array to decimalintconvert(intarr[]){intsum=0;for(inti=0; i<COL; i++){sum+=pow(2,i)*arr[i];}returnsum;}//print the column represented as integersvoidprint(intp){for(inti=0; i<COL; i++){cout<<p%2<<" ";p/=2;}cout<<endl;}// Default Constructor definition.BST :: BST() : data(0), left(NULL), right(NULL){}// Parameterized Constructor definition.BST :: BST(intvalue){data = value;left = right = NULL;}// Insert function definition.BST* BST :: Insert(BST *root,intvalue){if(!root){// Insert the first node, if root is NULL.returnnewBST(value);}//if the value is presentif(value == root->data)returnroot;// Insert data.if(value > root->data){// Insert right node data, if the 'value'// to be inserted is greater than 'root' node data.// Process right nodes.root->right = Insert(root->right, value);}else{// Insert left node data, if the 'value'// to be inserted is greater than 'root' node data.// Process left nodes.root->left = Insert(root->left, value);}// Return 'root' node, after insertion.returnroot;}// Inorder traversal function.// This gives data in sorted order.voidBST :: Inorder(BST *root){if(!root){return;}Inorder(root->left);print( root->data );Inorder(root->right);}// The main function that prints// all unique rows in a given matrix.voidfindUniqueRows(intM[ROW][COL]){BST b, *root = NULL;//Traverse through the matrixfor(inti=0; i<ROW; i++){//insert the row into BSTroot=b.Insert(root,convert(M[i]));}b.Inorder(root);}// Driver Codeintmain(){intM[ROW][COL] = {{0, 1, 0, 0, 1},{1, 0, 1, 1, 0},{0, 1, 0, 0, 1},{1, 0, 1, 0, 0}};findUniqueRows(M);return0;}Java
// Given a binary matrix of M X N of integers,// you need to return only unique rows of binary arrayimportjava.util.*;classGFG{staticclassBST {intdata;BST left,right;BST(intv){this.data = v;this.left =this.right =null;}}finalstaticintROW =4;finalstaticintCOL =5;// convert array to decimalstaticintconvert(intarr[]){intsum =0;for(inti =0; i < COL; i++){sum += Math.pow(2,i)*arr[i];}returnsum;}// print the column represented as integersstaticvoidprint(intp){for(inti =0; i < COL; i++){System.out.print(p%2+" ");p /=2;}System.out.println();}// Insert function definition.staticBST Insert(BST root,intvalue){if(root ==null){// Insert the first node, if root is null.returnnewBST(value);}//if the value is presentif(value == root.data)returnroot;// Insert data.if(value > root.data){// Insert right node data, if the 'value'// to be inserted is greater than 'root' node data.// Process right nodes.root.right = Insert(root.right, value);}else{// Insert left node data, if the 'value'// to be inserted is greater than 'root' node data.// Process left nodes.root.left = Insert(root.left, value);}// Return 'root' node, after insertion.returnroot;}// Inorder traversal function.// This gives data in sorted order.staticvoidInorder(BST root){if(root ==null){return;}Inorder(root.left);print( root.data );Inorder(root.right);}// The main function that prints// all unique rows in a given matrix.staticvoidfindUniqueRows(intM[][]){BST b, root =null;// Traverse through the matrixfor(inti =0; i < ROW; i++){// insert the row into BSTroot=Insert(root, convert(M[i]));}Inorder(root);}// Driver Codepublicstaticvoidmain(String[] args){intM[][] = {{0,1,0,0,1},{1,0,1,1,0},{0,1,0,0,1},{1,0,1,0,0}};findUniqueRows(M);}}// This code is contributed by Rajput-JiC#
// Given a binary matrix of M X N of integers,// you need to return only unique rows of binary arrayusingSystem;usingSystem.Collections.Generic;publicclassGFG{publicclassBST {publicintdata;publicBST left,right;publicBST(intv){this.data = v;this.left =this.right =null;}}readonlystaticintROW = 4;readonlystaticintCOL = 5;// convert array to decimalstaticintconvert(int[]arr){intsum = 0;for(inti = 0; i < COL; i++){sum += (int)Math.Pow(2,i)*arr[i];}returnsum;}// print the column represented as integersstaticvoidprint(intp){for(inti = 0; i < COL; i++){Console.Write(p%2+" ");p /= 2;}Console.WriteLine();}// Insert function definition.staticBST Insert(BST root,intvalue){if(root ==null){// Insert the first node, if root is null.returnnewBST(value);}// if the value is presentif(value == root.data)returnroot;// Insert data.if(value > root.data){// Insert right node data, if the 'value'// to be inserted is greater than 'root' node data.// Process right nodes.root.right = Insert(root.right, value);}else{// Insert left node data, if the 'value'// to be inserted is greater than 'root' node data.// Process left nodes.root.left = Insert(root.left, value);}// Return 'root' node, after insertion.returnroot;}// Inorder traversal function.// This gives data in sorted order.staticvoidInorder(BST root){if(root ==null){return;}Inorder(root.left);print( root.data );Inorder(root.right);}publicstaticint[] GetRow(int[,] matrix,introw){varrowLength = matrix.GetLength(1);varrowVector =newint[rowLength];for(vari = 0; i < rowLength; i++)rowVector[i] = matrix[row, i];returnrowVector;}// The main function that prints// all unique rows in a given matrix.staticvoidfindUniqueRows(int[,]M){BST b, root =null;// Traverse through the matrixfor(inti = 0; i < ROW; i++){// insert the row into BSTint[] row = GetRow(M,i);root=Insert(root, convert(row));}Inorder(root);}// Driver CodepublicstaticvoidMain(String[] args){int[,]M = {{0, 1, 0, 0, 1},{1, 0, 1, 1, 0},{0, 1, 0, 0, 1},{1, 0, 1, 0, 0}};findUniqueRows(M);}}// This code contributed by Rajput-JiPython3
# Given a binary matrix of M X N of integers,# you need to return only unique rows of binary arrayROW=4COL=5# print the column represented as integersdef(p):foriinrange(COL):(p%2,end=" ")p=int(p//2)("")classBST:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Insert function definition.defInsert(self,root, value):if(notroot):# Insert the first node, if root is NULL.returnBST(value)#if the value is presentif(value==root.data):returnroot# Insert data.if(value > root.data):# Insert right node data, if the 'value'# to be inserted is greater than 'root' node data.# Process right nodes.root.right=self.Insert(root.right, value)else:# Insert left node data, if the 'value'# to be inserted is greater than 'root' node data.# Process left nodes.root.left=self.Insert(root.left, value)# Return 'root' node, after insertion.returnroot# Inorder traversal function.# This gives data in sorted order.defInorder(self,root):if(notroot):returnself.Inorder(root.left);( root.data );self.Inorder(root.right)# convert array to decimaldefconvert(arr):sum=0foriinrange(COL):sum+=pow(2,i)*arr[i]returnsum# The main function that prints# all unique rows in a given matrix.deffindUniqueRows(M):b,root=BST(0),None#Traverse through the matrixforiinrange(ROW):#insert the row into BSTroot=b.Insert(root,convert(M[i]))b.Inorder(root)# Driver CodeM=[[0,1,0,0,1],[1,0,1,1,0],[0,1,0,0,1],[1,0,1,0,0]]findUniqueRows(M)# This code is contributed by shinjanpatraJavascript
<script>// Given a binary matrix of M X N of integers,// you need to return only unique rows of binary arrayvarROW = 4varCOL = 5class BST{constructor(data){this.data = data;this.left =null;this.right =null;}// Insert function definition.Insert(root, value){if(!root){// Insert the first node, if root is NULL.returnnewBST(value);}//if the value is presentif(value == root.data)returnroot;// Insert data.if(value > root.data){// Insert right node data, if the 'value'// to be inserted is greater than 'root' node data.// Process right nodes.root.right =this.Insert(root.right, value);}else{// Insert left node data, if the 'value'// to be inserted is greater than 'root' node data.// Process left nodes.root.left =this.Insert(root.left, value);}// Return 'root' node, after insertion.returnroot;}// Inorder traversal function.// This gives data in sorted order.Inorder(root){if(!root){return;}this.Inorder(root.left);print( root.data );this.Inorder(root.right);}};// convert array to decimalfunctionconvert(arr){varsum=0;for(vari=0; i<COL; i++){sum+=Math.pow(2,i)*arr[i];}returnsum;}// print the column represented as integersfunctionprint(p){for(vari=0; i<COL; i++){document.write(p%2 +" ");p=parseInt(p/2);}document.write("<br>");}// The main function that prints// all unique rows in a given matrix.functionfindUniqueRows(M){varb =newBST(0),root =null;//Traverse through the matrixfor(vari=0; i<ROW; i++){//insert the row into BSTroot=b.Insert(root,convert(M[i]));}b.Inorder(root);}// Driver CodevarM = [[0, 1, 0, 0, 1],[1, 0, 1, 1, 0],[0, 1, 0, 0, 1],[1, 0, 1, 0, 0]];findUniqueRows(M);// This code is contributed by rutvik_56.</script>Output1 0 1 0 0 1 0 1 1 0 0 1 0 0 1Complexity Analysis:
- Time complexity: O( ROW x COL + ROW x log( ROW ) ).
To traverse the matrix time complexity is O( ROW x COL) and to insert them into BST time complexity is O(log ROW) for each row. So overall time complexity is O( ROW x COL + ROW x log( ROW ) )- Auxiliary Space: O( ROW ).
To store the BST O(ROW) space is needed.Method 3: This method uses Trie data structure to solve the above problem. Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length). If we store keys in the binary search tree, a well-balanced BST will need time proportional to M * log N, where M is maximum string length and N is the number of keys in the tree. Using Trie, we can search the key in O(M) time. However, the penalty is on Trie storage requirements.
Note: This method will lead to Integer Overflow if the number of columns is large.
Approach:
Since the matrix is boolean, a variant of Trie data structure can be used where each node will be having two children one for 0 and other for 1. Insert each row in the Trie. If the row is already there, don’t print the row. If the row is not there in Trie, insert it in Trie and print it.Algorithm:
- Create a Trie where rows can be stored.
- Traverse through the matrix and insert the row into the Trie.
- Trie cannot store duplicate entries so the duplicates will be removed
- Traverse the Trie and print the rows.
Implementation:
C++
// Given a binary matrix of M X N of integers,// you need to return only unique rows of binary array#include <bits/stdc++.h>usingnamespacestd;#define ROW 4#define COL 5// A Trie nodeclassNode{public:boolisEndOfCol;Node *child[2];// Only two children needed for 0 and 1} ;// A utility function to allocate memory// for a new Trie nodeNode* newNode(){Node* temp =newNode();temp->isEndOfCol = 0;temp->child[0] = temp->child[1] = NULL;returntemp;}// Inserts a new matrix row to Trie.// If row is already present,// then returns 0, otherwise insets the row and// return 1boolinsert(Node** root,int(*M)[COL],introw,intcol ){// base caseif(*root == NULL)*root = newNode();// Recur if there are more entries in this rowif(col < COL)returninsert (&((*root)->child[M[row][col]]),M, row, col + 1);else// If all entries of this row are processed{// unique row found, return 1if(!((*root)->isEndOfCol))return(*root)->isEndOfCol = 1;// duplicate row found, return 0return0;}}// A utility function to print a rowvoidprintRow(int(*M)[COL],introw){inti;for(i = 0; i < COL; ++i)cout << M[row][i] <<" ";cout << endl;}// The main function that prints// all unique rows in a given matrix.voidfindUniqueRows(int(*M)[COL]){Node* root = NULL;// create an empty Trieinti;// Iterate through all rowsfor(i = 0; i < ROW; ++i)// insert row to TRIEif(insert(&root;, M, i, 0))// unique row found, print itprintRow(M, i);}// Driver Codeintmain(){intM[ROW][COL] = {{0, 1, 0, 0, 1},{1, 0, 1, 1, 0},{0, 1, 0, 0, 1},{1, 0, 1, 0, 0}};findUniqueRows(M);return0;}// This code is contributed by rathbhupendraC
//Given a binary matrix of M X N of integers, you need to return only unique rows of binary array#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#define ROW 4#define COL 5// A Trie nodetypedefstructNode{boolisEndOfCol;structNode *child[2];// Only two children needed for 0 and 1} Node;// A utility function to allocate memory for a new Trie nodeNode* newNode(){Node* temp = (Node *)malloc(sizeof( Node ) );temp->isEndOfCol = 0;temp->child[0] = temp->child[1] = NULL;returntemp;}// Inserts a new matrix row to Trie. If row is already// present, then returns 0, otherwise insets the row and// return 1boolinsert( Node** root,int(*M)[COL],introw,intcol ){// base caseif( *root == NULL )*root = newNode();// Recur if there are more entries in this rowif( col < COL )returninsert ( &( (*root)->child[ M[row][col] ] ), M, row, col+1 );else// If all entries of this row are processed{// unique row found, return 1if( !( (*root)->isEndOfCol ) )return(*root)->isEndOfCol = 1;// duplicate row found, return 0return0;}}// A utility function to print a rowvoidprintRow(int(*M)[COL],introw ){inti;for( i = 0; i < COL; ++i )printf("%d ", M[row][i] );printf("\n");}// The main function that prints all unique rows in a// given matrix.voidfindUniqueRows(int(*M)[COL] ){Node* root = NULL;// create an empty Trieinti;// Iterate through all rowsfor( i = 0; i < ROW; ++i )// insert row to TRIEif( insert(&root;, M, i, 0) )// unique row found, print itprintRow( M, i );}// Driver program to test above functionsintmain(){intM[ROW][COL] = {{0, 1, 0, 0, 1},{1, 0, 1, 1, 0},{0, 1, 0, 0, 1},{1, 0, 1, 0, 0}};findUniqueRows( M );return0;}Output0 1 0 0 1 1 0 1 1 0 1 0 1 0 0Complexity Analysis:
- Time complexity: O( ROW x COL ).
To traverse the matrix and insert in the trie the time complexity is O( ROW x COL). This method has better time complexity. Also, the relative order of rows is maintained while printing but it takes a toll on space.- Auxiliary Space: O( ROW x COL ).
To store the Trie O(ROW x COL) space complexity is needed.Method 4: This method uses HashSet data structure to solve the above problem. The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means that the class does not guarantee the constant order of elements over time. This class permits the null element. The class offers constant time performance for the basic operations like add, remove, contains and size assuming the hash function disperses the elements properly among the buckets.
Approach: In this method convert the whole row into a single String and then if check it is already present in the HashSet or not. If the row is present then we will leave it otherwise we will print unique row and add it to HashSet.
Algorithm:
- Create a HashSet where rows can be stored as a String.
- Traverse through the matrix and insert the row as String into the HashSet.
- HashSet cannot store duplicate entries so the duplicates will be removed
- Traverse the HashSet and print the rows.
Implementation:
C++
// C++ code to print unique row in a// given binary matrix#include<bits/stdc++.h>usingnamespacestd;voidprintArray(intarr[][5],introw,intcol){unordered_set<string> uset;for(inti = 0; i < row; i++){string s ="";for(intj = 0; j < col; j++)s += to_string(arr[i][j]);if(uset.count(s) == 0){uset.insert(s);cout << s << endl;}}}// Driver codeintmain(){intarr[][5] = {{0, 1, 0, 0, 1},{1, 0, 1, 1, 0},{0, 1, 0, 0, 1},{1, 1, 1, 0, 0}};printArray(arr, 4, 5);}// This code is contributed by// rathbhupendraJava
// Java code to print unique row in a// given binary matriximportjava.util.HashSet;publicclassGFG {publicstaticvoidprintArray(intarr[][],introw,intcol){HashSet<String> set =newHashSet<String>();for(inti =0; i < row; i++){String s ="";for(intj =0; j < col; j++)s += String.valueOf(arr[i][j]);if(!set.contains(s)) {set.add(s);System.out.println(s);}}}// Driver codepublicstaticvoidmain(String[] args) {intarr[][] = { {0,1,0,0,1},{1,0,1,1,0},{0,1,0,0,1},{1,1,1,0,0} };printArray(arr,4,5);}}Python3
# Python3 code to print unique row in a# given binary matrixdefprintArray(matrix):rowCount=len(matrix)ifrowCount==0:returncolumnCount=len(matrix[0])ifcolumnCount==0:returnrow_output_format=" ".join(["%s"]*columnCount)printed={}forrowinmatrix:routput=row_output_format%tuple(row)ifroutputnotinprinted:printed[routput]=True(routput)# Driver Codemat=[[0,1,0,0,1],[1,0,1,1,0],[0,1,0,0,1],[1,1,1,0,0]]printArray(mat)# This code is contributed by myronwalkerC#
usingSystem;usingSystem.Collections.Generic;// c# code to print unique row in a// given binary matrixpublicclassGFG{publicstaticvoidprintArray(int[][] arr,introw,intcol){HashSet<string>set=newHashSet<string>();for(inti = 0; i < row; i++){strings ="";for(intj = 0; j < col; j++){s += arr[i][j].ToString();}if(!set.Contains(s)){set.Add(s);Console.WriteLine(s);}}}// Driver codepublicstaticvoidMain(string[] args){int[][] arr =newint[][]{newint[] {0, 1, 0, 0, 1},newint[] {1, 0, 1, 1, 0},newint[] {0, 1, 0, 0, 1},newint[] {1, 1, 1, 0, 0}};printArray(arr, 4, 5);}}// This code is contributed by Shrikant13Javascript
<script>// Javascript code to print unique row in a// given binary matrixfunctionprintArray(arr,row,col){let set =newSet();for(let i = 0; i < row; i++){let s ="";for(let j = 0; j < col; j++)s += (arr[i][j]).toString();if(!set.has(s)) {set.add(s);document.write(s+"<br>");}}}// Driver codelet arr = [[0, 1, 0, 0, 1],[1, 0, 1, 1, 0],[0, 1, 0, 0, 1],[1, 1, 1, 0, 0]];printArray(arr, 4, 5);// This code is contributed by avanitrachhadiya2155</script>Output01001 10110 11100Complexity Analysis:
- Time complexity: O( ROW x COL ).
To traverse the matrix and insert in the HashSet the time complexity is O( ROW x COL)- Auxiliary Space: O( ROW ).
To store the HashSet O(ROW x COL) space complexity is needed.My Personal Notes arrow_drop_upRecommended ArticlesPage :Article Contributed By :Improved By :Article Tags :




.png)
