Unique rows in boolean matrix | Practice | GeeksforGeeks

Given a binary matrix your task is to find all unique rows of the given matrix. 
Example 1:
Input:
row = 3, col = 4 
M[][] = {{1 1 0 1},{1 0 0 1},{1 1 0 1}}
Output: 1 1 0 1 $1 0 0 1 $
Explanation: Above the matrix of size 3x4
looks like
1 1 0 1
1 0 0 1
1 1 0 1
The two unique rows are 1 1 0 1 and
1 0 0 1 .

Your Task:
You only need to implement the given function uniqueRow(). The function takes three arguments the first argument is a matrix M and the next two arguments are row and col denoting the rows and columns of the matrix. The function should return the list of the unique row of the martrix. Do not read input, instead use the arguments given in the function.
Note: The drivers code print the rows "$" separated.
Expected Time Complexity: O(row * col)
Expected Auxiliary Space: O(row * col)
Constraints:
1<=row,col<=40
0<=M[][]<=1
0
chowdasandeepin 8 hours
def uniqueRow(row, col, matrix):   #complete the function   l=[]   c=0   while c<row*col:       x=matrix[c:c+col]       if x not in l:           l.append(x)       c+=col   return l          
+1
bhardwajji1 week ago
vector<vector<int>> uniqueRow(int mat[MAX][MAX],int row,int col)
{
    unordered_set<string>map;
    vector<vector<int>>ans;
    
    for(int i=0 ;i<row ; i++){
        string temp= "";
        vector<int>vec;
        for(int j=0 ;j<col ; j++){
            temp+=to_string(mat[i][j]);
            vec.push_back(mat[i][j]);
        }
        if(map.find(temp) == map.end()){
            ans.push_back(vec);
            map.insert(temp);
        }
    }
    
    return ans;
    
}
+1
milindprajapatmst191 month ago
1st Solution Using set:
Time Complexity: O(row x col)
Space Complexity: O(row x col)

# define ll long long
vector<vector<int>> uniqueRow(int M[MAX][MAX], int row, int col) {
    unordered_set<ll> S;
    vector<vector<int>> arr;
    for (int i = 0; i < row; i++) {
        ll _sum = 0;
        vector<int> _arr;
        for (int j = 0; j < col; j++) {
            _sum *= 2;
            _sum += M[i][j];
            _arr.push_back(M[i][j]);
        }
        if (S.find(_sum) == S.end())
            arr.push_back(_arr);
        S.insert(_sum);
    }
    return arr;
}

2nd Solution Using Trie:
Time Complexity: O(row x col)
Space Complexity: O(row x col)

class Node {
public:
    bool end;
    Node *left, *right;
    Node() {
        this->end = false;
        this->left = nullptr; this->right = nullptr;
    }
};

class Trie {
public:
    Node *root;
    vector<vector<int>> unique;
    void insert(int arr[], int n) {
        vector<int> _arr;
        Node *curr = root;
        for (int i = 0; i < n; i++) {
            _arr.push_back(arr[i]);
            if (arr[i]) {
                if (!curr->right)
                    curr->right = new Node();
                curr = curr->right;
            }
            else {
                if (!curr->left)
                    curr->left = new Node();
                curr = curr->left;
            }
        }
        if (!curr->end) {
            curr->end = true;
            unique.push_back(_arr);
        }
    }
    Trie() {
        this->root = new Node();
    }
};

vector<vector<int>> uniqueRow(int M[MAX][MAX], int row, int col) {
    Trie T;
    for (int i = 0; i < row; i++)
        T.insert(M[i], col);
    return T.unique;
}
0
sunilsaikumar1 month ago
2 Solutions Using Trie+DFS And Set In Python
 
Using Trie+DFS
 
class TrieNode:
   def __init__(self):
       self.NodeLinks = {}
       self.Count = 0
class Trie:
   def __init__(self):
       self.Root = TrieNode()
       
   def insertRow(self,Row):
       Node = self.Root
       for bit in Row:
           if(bit not in Node.NodeLinks):
               Node.NodeLinks[bit] = TrieNode()
           Node = Node.NodeLinks[bit]
       Node.Count += 1
       
   def printUnique(self,Row):
       Node = self.Root
       for bit in Row:
           Node = Node.NodeLinks[bit]
       if(Node.Count != 0):
           Node.Count = 0 
           return True
       return False
       
def uniqueRow(row, col, matrix):
   Tr = Trie()
   subMat = []
   for i in range(0,len(matrix),col):
       subMat.append(matrix[i:i+col])
   FinRes = []
   for Row in subMat:
       Tr.insertRow(Row)
   for Row in subMat:
       if(Tr.printUnique(Row)):
           FinRes.append(Row)
   return FinRes
 
Using Set
 
def uniqueRow(row, col, matrix):
   Set,Res = set(),[]
   for i in range(0,len(matrix),col):
       subMat = matrix[i:i+col]
       if(tuple(subMat) not in Set):
           Res.append(subMat)
           Set.add(tuple(subMat))
   return Res
0
visitant2 months ago
vector<vector<int>> uniqueRow(int M[MAX][MAX],int row,int col)
{
//Your code here
vector <vector <int>> a;
unordered_set <string> c;


for(int i=0; i< row; i++)
{
    string s = "";
    vector <int> b;
    for(int j=0;j<col; j++)
    {
        if(M[i][j] == 0)
        {
            s.push_back('a');
        }
        else 
        {
            s.push_back('b');
        }
        b.push_back(M[i][j]);
    }
    if(c.find(s) == c.end())
    {
        c.insert(s);
        a.push_back(b);
    }
}

return a;
}
+2
aloksinghbais022 months ago
C++ solution using trie having time complexity as O(row*(2*col)) and space complexity as O(row*col) is as follows :- 
 
Execution Time :- 0.0 / 1.0 sec
 
struct Node{   Node *links[2] = {nullptr};   bool flag = false;      bool containsKey(int x){       return links[x] != nullptr;   }      void put(int x,Node *node){       links[x] = node;   }      Node* getKey(int x){       return links[x];   }      void setEnd(){       flag = true;   }      bool isEnd(){       return (flag);   }};
class trie{   private:   Node *root;      public:   trie(){       root = new Node();   }      void insert(vector<int> arr){       Node *node = root;       for(int i = 0; i < arr.size(); i++){           if(!node->containsKey(arr[i])){               node->put(arr[i],new Node());           }           node = node->getKey(arr[i]);       }       node->setEnd();   }      bool search(vector<int> arr){       Node *node = root;       for(int i = 0; i < arr.size(); i++){           if(!node->containsKey(arr[i])){               return (false);           }           node = node->getKey(arr[i]);       }       return node->isEnd();   }};
vector<vector<int>> uniqueRow(int M[MAX][MAX],int row,int col){   trie tri;   vector<vector<int>> ans;   for(int i = 0; i < row; i++){       vector<int> v;       for(int j = 0; j < col; j++){           v.push_back(M[i][j]);       }              if(tri.search(v)) continue;       tri.insert(v);       ans.push_back(v);   }      return (ans);}
0
sequeirahansel2 months ago
My solution using a trie:
typedef struct Node{
    struct Node* arr[2];
    bool flag;
    Node(){
        for(int i=0;i<2;i++){
            arr[i] = NULL;
        }
        flag = false;
    }
}Node;

class Trie{
    public:
    
        bool isPresent(Node* node, int arr[], int n){
            for(int i=0;i<n;i++){
                int idx = arr[i];
                if(!node->arr[idx]){
                    return false;
                }
                node = node->arr[idx];
            }
            return node->flag;
        }
        
        void insert(Node* node, int arr[], int n){
            for(int i=0;i<n;i++){
                int idx = arr[i];
                if(!node->arr[idx]){
                    node->arr[idx] = new Node();
                } 
                node = node->arr[idx];
            }
            node->flag = true;
        }
        
};


/*You are required to complete this function*/
vector<vector<int>> uniqueRow(int M[MAX][MAX],int row,int col)
{
//Your code here
    Trie t;
    Node* root = new Node();
    vector<vector<int>> res;
    for(int i=0;i<row;i++){
        if(!t.isPresent(root, M[i], col)){
            t.insert(root, M[i], col);
            vector<int> inner(M[i], M[i]+col);
            res.push_back(inner);
        }
    }
    
    return res;
}
+2
himanshujain4572 months ago
Simple Java Solution Using Trie:
class GfG{ static  class TrieNode{       int wordend=0;       TrieNode child[]=new TrieNode[2];       TrieNode()       {          for(int i=0;i<2;i++)          {              child[i]=null;          }       }   }  static  TrieNode root=new TrieNode();  static  void BuildTrie(int a[][],int r, int c)   {       for(int i=0;i<r;i++)       {       TrieNode temp=root;           for(int j=0;j<c;j++)           {               if(temp.child[a[i][j]]==null)               {                   temp.child[a[i][j]]=new TrieNode();               }               temp=temp.child[a[i][j]];                          }           temp.wordend=1;       }   }   public static ArrayList<ArrayList<Integer>> uniqueRow(int a[][],int r, int c)   {       ArrayList<ArrayList<Integer>>ans=new ArrayList<ArrayList<Integer>>();       BuildTrie(a,r,c);       for(int i=0;i<r;i++)       {       ArrayList<Integer>t=new ArrayList<Integer>();           TrieNode temp=root;           for(int j=0;j<c;j++)           {               temp=temp.child[a[i][j]];               t.add(a[i][j]);                          }           if(temp.wordend==1)           {               ans.add(t);               temp.wordend=0;           }       }       return ans;          }}
 
0
himanshujain4572 months ago
Simple Java Solution Using HashSet:
class GfG{   public static ArrayList<ArrayList<Integer>> uniqueRow(int a[][],int r, int c)   {       ArrayList<ArrayList<Integer>>ans=new ArrayList<>();       Set<ArrayList<Integer>>st=new HashSet<>();       for(int i=0;i<r;i++)       {           ArrayList<Integer>ap=new ArrayList<>();           for(int j=0;j<c;j++)           {               ap.add(a[i][j]);           }           if(!st.contains(ap))           {           st.add(ap);           ans.add(ap);                          }       }             return ans;   }}
0
himanshujain457
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.