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
Method 1 (Simple)
A simple approach is 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, don’t print it. If the current row doesn’t match with any row, print it.
Time complexity: O( ROW^2 x COL )
Auxiliary Space: O( 1 )
Method 2 (Use Binary Search Tree)
Find the decimal equivalent of each row and insert it into BST. Each node of the BST will contain two fields, one field for the decimal value, other for row number. Do not insert a node if it is duplicated. Finally, traverse the BST and print the corresponding rows.
Time complexity: O( ROW x COL + ROW x log( ROW ) )
Auxiliary Space: O( ROW )
This method will lead to Integer Overflow if number of columns is large.
Method 3 (Use Trie data structure)
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 row is not there in Trie, insert it in Trie and print it.
Below is C implementation of method 3.
//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 node typedef struct Node { bool isEndOfCol; struct Node *child[2]; // Only two children needed for 0 and 1 } Node; // A utility function to allocate memory for a new Trie node Node* newNode() { Node* temp = (Node *) malloc ( sizeof ( Node ) ); temp->isEndOfCol = 0; temp->child[0] = temp->child[1] = NULL; return temp; } // Inserts a new matrix row to Trie. If row is already // present, then returns 0, otherwise insets the row and // return 1 bool insert( Node** root, int (*M)[COL], int row, int col ) { // base case if ( *root == NULL ) *root = newNode(); // Recur if there are more entries in this row if ( col < COL ) return insert ( &( (*root)->child[ M[row][col] ] ), M, row, col+1 ); else // If all entries of this row are processed { // unique row found, return 1 if ( !( (*root)->isEndOfCol ) ) return (*root)->isEndOfCol = 1; // duplicate row found, return 0 return 0; } } // A utility function to print a row void printRow( int (*M)[COL], int row ) { int i; for ( i = 0; i < COL; ++i ) printf ( "%d " , M[row][i] ); printf ( "
" ); } // The main function that prints all unique rows in a // given matrix. void findUniqueRows( int (*M)[COL] ) { Node* root = NULL; // create an empty Trie int i; // Iterate through all rows for ( i = 0; i < ROW; ++i ) // insert row to TRIE if ( insert(&root, M, i, 0) ) // unique row found, print it printRow( M, i ); } // Driver program to test above functions int main() { int M[ROW][COL] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0} }; findUniqueRows( M ); return 0; } |
Output:
0 1 0 0 1 1 0 1 1 0 1 0 1 0 0
Time complexity: O( ROW x COL )
Auxiliary Space: O( ROW x COL )
This method has better time complexity. Also, relative order of rows is maintained while printing.
Method 4 (Use HashSet data structure)
In this method convert the whole row into a single String and then check it is already present in HashSet or not. If row is present then we will leave it otherwise we will print unique row and add it to HashSet.
Thanks, Anshuman Kaushik for suggesting this method.
C/C++
// C++ code to print unique row in a // given binary matrix #include<bits/stdc++.h> using namespace std; void printArray( int arr[][5], int row, int col) { unordered_set<string> uset; for ( int i = 0; i < row; i++) { string s = "" ; for ( int j = 0; j < col; j++) s += to_string(arr[i][j]); if (uset.count(s) == 0) { uset.insert(s); cout << s << endl; } } } // Driver code int main() { int arr[][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 // rathbhupendra |
Java
// Java code to print unique row in a // given binary matrix import java.util.HashSet; public class GFG { public static void printArray( int arr[][], int row, int col) { HashSet<String> set = new HashSet<String>(); for ( int i = 0 ; i < row; i++) { String s = "" ; for ( int j = 0 ; j < col; j++) s += String.valueOf(arr[i][j]); if (!set.contains(s)) { set.add(s); System.out.println(s); } } } // Driver code public static void main(String[] args) { int 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 ); } } |
Python3
# Python3 code to print unique row in a
# given binary matrix
def printArray(matrix):
rowCount = len(matrix)
if rowCount == 0:
return
columnCount = len(matrix[0])
if columnCount == 0:
return
row_output_format = ” “.join([“%s”] * columnCount)
printed = {}
for row in matrix:
routput = row_output_format % tuple(row)
if routput not in printed:
printed[routput] = True
print(routput)
# Driver Code
mat = [[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 myronwalker
C#
using System; using System.Collections.Generic; // c# code to print unique row in a // given binary matrix public class GFG { public static void printArray( int [][] arr, int row, int col) { HashSet< string > set = new HashSet< string >(); for ( int i = 0; i < row; i++) { string s = "" ; for ( int j = 0; j < col; j++) { s += arr[i][j].ToString(); } if (! set .Contains(s)) { set .Add(s); Console.WriteLine(s); } } } // Driver code public static void Main( string [] args) { int [][] arr = new int [][] { new int [] {0, 1, 0, 0, 1}, new int [] {1, 0, 1, 1, 0}, new int [] {0, 1, 0, 0, 1}, new int [] {1, 1, 1, 0, 0} }; printArray(arr, 4, 5); } } // This code is contributed by Shrikant13 |
Output:
01001 10110 11100
Time complexity: O( ROW x COL )
Auxiliary Space: O(ROW)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
leave a comment
0 Comments