The Wayback Machine - https://web.archive.org/web/20240910174433/https://www.geeksforgeeks.org/print-unique-rows/
Open In App

Print unique rows in a given Binary matrix

Last Updated : 31 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
48.36%
49.5K

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.
Recommended Practice

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: 

  1. Traverse the matrix row-wise
  2. For each row check if there is any similar row less than the current index.
  3. If any two rows are similar then do not print the row.
  4. 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>
using namespace std;
#define ROW 4
#define COL 5
 
// The main function that prints
// all unique rows in a given matrix.
void findUniqueRows(int M[ROW][COL])
{
    //Traverse through the matrix
    for(int i=0; i<ROW; i++)
    {
        int flag=0;
         
        //check if there is similar column
        //is already printed, i.e if i and
        //jth column match.
        for(int j=0; j<i; j++)
        {
            flag=1;
             
            for(int k=0; k<=COL; k++)
            if(M[i][k]!=M[j][k])
                flag=0;
             
            if(flag==1)
            break;
        }
         
        //if no row is similar
        if(flag==0)
        {
            //print the row
            for(int j=0; j<COL; j++)
                cout<<M[i][j]<<" ";
            cout<<endl;
        }
    }
}
 
// Driver Code
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;
}


Java




// Given a binary matrix of M X N
// of integers, you need to return
// only unique rows of binary array
import java.io.*;
class GFG{
     
static int ROW = 4;
static int COL = 5;
 
// Function that prints all
// unique rows in a given matrix.
static void findUniqueRows(int M[][])
{
     
    // Traverse through the matrix
    for(int i = 0; i < ROW; i++)
    {
        int flag = 0;
         
        // Check if there is similar column
        // is already printed, i.e if i and
        // jth column match.
        for(int j = 0; j < i; j++)
        {
            flag = 1;
 
            for(int k = 0; k < COL; k++)
                if (M[i][k] != M[j][k])
                    flag = 0;
 
            if (flag == 1)
                break;
        }
 
        // If no row is similar
        if (flag == 0)
        {
             
            // Print the row
            for(int j = 0; j < COL; j++)
                System.out.print(M[i][j] + " ");
 
            System.out.println();
        }
    }
}
 
// Driver Code
public static void main(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 is contributed by mark_85


Python3




# Given a binary matrix of M X N of
# integers, you need to return only
# unique rows of binary array
ROW = 4
COL = 5
 
# The main function that prints
# all unique rows in a given matrix.
def findUniqueRows(M):
     
    # Traverse through the matrix
    for i in range(ROW):
        flag = 0
 
        # Check if there is similar column
        # is already printed, i.e if i and
        # jth column match.
        for j in range(i):
            flag = 1
 
            for k in range(COL):
                if (M[i][k] != M[j][k]):
                    flag = 0
 
            if (flag == 1):
                break
 
        # If no row is similar
        if (flag == 0):
             
            # Print the row
            for j in range(COL):
                print(M[i][j], end = " ")
                 
            print()   
 
# Driver Code
if __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 29


C#




// Given a binary matrix of M X N 
// of integers, you need to return
// only unique rows of binary array  
using System;
 
class GFG{
     
static int ROW = 4;
static int COL = 5;
   
// Function that prints all 
// unique rows in a given matrix.
static void findUniqueRows(int[,] M)
{
     
    // Traverse through the matrix
    for(int i = 0; i < ROW; i++)
    {
        int flag = 0;
           
        // Check if there is similar column
        // is already printed, i.e if i and
        // jth column match.
        for(int j = 0; j < i; j++) 
        {
            flag = 1;
             
            for(int k = 0; k < COL; k++)
                if (M[i, k] != M[j, k])
                    flag = 0;
   
            if (flag == 1)
                break;
        }
   
        // If no row is similar
        if (flag == 0)
        {
             
            // Print the row
            for(int j = 0; j < COL; j++)
                Console.Write(M[i, j] + " ");
   
            Console.WriteLine();
        }
    }
}
 
// Driver code
static void Main()
{
    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 divyeshrabadiya07


Javascript




<script>
// Given a binary matrix of M X N
// of integers, you need to return
// only unique rows of binary array
     
    let ROW = 4;
    let COL = 5;
     
    // Function that prints all
// unique rows in a given matrix.
    function findUniqueRows(M)
    {
        // Traverse through the matrix
    for(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 similar
        if (flag == 0)
        {
               
            // Print the row
            for(let j = 0; j < COL; j++)
                document.write(M[i][j] + " ");
   
            document.write("<br>");
        }
    }
    }
     
    // Driver Code
    let 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>


Output

0 1 0 0 1 
1 0 1 1 0 
1 0 1 0 0 

Complexity 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: 

  1. 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.
  2. Traverse through the matrix and insert the row into the BST.
  3. 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>
using namespace std;
#define ROW 4
#define COL 5
 
class BST
{
    int data;
    BST *left, *right;
 
    public:
     
    // Default constructor.
    BST();
     
    // Parameterized constructor.
    BST(int);
     
    // Insert function.
    BST* Insert(BST *, int);
     
    // Inorder traversal.
    void Inorder(BST *);
};
 
//convert array to decimal
int convert(int arr[])
{
    int sum=0;
     
    for(int i=0; i<COL; i++)
    {
        sum+=pow(2,i)*arr[i];
    }
    return sum;
}
 
//print the column represented as integers
void print(int p)
{
    for(int i=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(int value)
{
    data = value;
    left = right = NULL;
}
 
// Insert function definition.
BST* BST :: Insert(BST *root, int value)
{
    if(!root)
    {
        // Insert the first node, if root is NULL.
        return new BST(value);
    }
     
    //if the value is present
    if(value == root->data)
     return root;
 
    // 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.
    return root;
}
 
// Inorder traversal function.
// This gives data in sorted order.
void BST :: 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.
void findUniqueRows(int M[ROW][COL])
{
     
    BST b, *root = NULL;
     
    //Traverse through the matrix
    for(int i=0; i<ROW; i++)
    {
        //insert the row into BST
        root=b.Insert(root,convert(M[i]));
    }
     
     
    //print
    b.Inorder(root);
     
}
 
// Driver Code
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;
}


Java




// Given a binary matrix of M X N of integers,
// you need to return only unique rows of binary array
import java.util.*;
 
class GFG{
  static class BST {
    int data;
    BST left,right;
    BST(int v){
      this.data = v;
      this.left = this.right = null;
    }
  }
  final  static int ROW = 4;
  final  static int COL = 5;
  // convert array to decimal
  static int convert(int arr[])
  {
    int sum = 0;
 
    for(int i = 0; i < COL; i++)
    {
      sum += Math.pow(2,i)*arr[i];
    }
    return sum;
  }
 
  // print the column represented as integers
  static void print(int p)
  {
    for(int i = 0; i < COL; i++)
    {
      System.out.print(p%2+" ");
      p /= 2;
    }
    System.out.println();
  }
 
 
 
  // Insert function definition.
  static BST Insert(BST root, int value)
  {
    if(root == null)
    {
      // Insert the first node, if root is null.
      return new BST(value);
    }
 
    //if the value is present
    if(value == root.data)
      return root;
 
    // 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.
    return root;
  }
 
  // Inorder traversal function.
  // This gives data in sorted order.
  static void Inorder(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.
  static void findUniqueRows(int M[][])
  {
 
    BST b, root = null;
 
    // Traverse through the matrix
    for(int i = 0; i < ROW; i++)
    {
      // insert the row into BST
      root=Insert(root, convert(M[i]));
    }
 
 
    //print
    Inorder(root);
 
  }
 
  // Driver Code
  public static void main(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 is contributed by Rajput-Ji


C#




// Given a binary matrix of M X N of integers,
// you need to return only unique rows of binary array
using System;
using System.Collections.Generic;
 
public class GFG{
  public class BST {
    public int data;
    public BST left,right;
    public BST(int v){
      this.data = v;
      this.left = this.right = null;
    }
  }
  readonly  static int ROW = 4;
  readonly  static int COL = 5;
   
  // convert array to decimal
  static int convert(int []arr)
  {
    int sum = 0;
 
    for(int i = 0; i < COL; i++)
    {
      sum += (int)Math.Pow(2,i)*arr[i];
    }
    return sum;
  }
 
  // print the column represented as integers
  static void print(int p)
  {
    for(int i = 0; i < COL; i++)
    {
      Console.Write(p%2+" ");
      p /= 2;
    }
    Console.WriteLine();
  }
 
 
 
  // Insert function definition.
  static BST Insert(BST root, int value)
  {
    if(root == null)
    {
      // Insert the first node, if root is null.
      return new BST(value);
    }
 
    // if the value is present
    if(value == root.data)
      return root;
 
    // 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.
    return root;
  }
 
  // Inorder traversal function.
  // This gives data in sorted order.
  static void Inorder(BST root)
  {
    if(root == null)
    {
      return;
    }
    Inorder(root.left);
    print( root.data );
    Inorder(root.right);
  }
 public static int[] GetRow(int[,] matrix, int row)
  {
    var rowLength = matrix.GetLength(1);
    var rowVector = new int[rowLength];
 
    for (var i = 0; i < rowLength; i++)
      rowVector[i] = matrix[row, i];
 
    return rowVector;
  }
  // The main function that prints
  // all unique rows in a given matrix.
  static void findUniqueRows(int [,]M)
  {
 
    BST b, root = null;
 
    // Traverse through the matrix
    for(int i = 0; i < ROW; i++)
    {
      // insert the row into BST
        int[] row = GetRow(M,i);
      root=Insert(root, convert(row));
    }
 
 
    //print
    Inorder(root);
 
  }
 
  // Driver Code
  public static void Main(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-Ji


Python3




# Given a binary matrix of M X N of integers,
# you need to return only unique rows of binary array
ROW = 4
COL = 5
 
# print the column represented as integers
def Print(p):
 
    for i in range(COL):
        print(p % 2 ,end = " ")
        p = int(p//2)
    print("")
 
class BST:
 
    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None
 
    # Insert function definition.
    def Insert(self,root, value):
 
        if(not root):
            # Insert the first node, if root is NULL.
            return BST(value)
         
        #if the value is present
        if(value == root.data):
            return root
     
        # 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.
        return root
 
    # Inorder traversal function.
    # This gives data in sorted order.
    def Inorder(self,root):
        if(not root):
            return
        self.Inorder(root.left);
        Print( root.data );
        self.Inorder(root.right)
 
# convert array to decimal
def convert(arr):
    sum=0
     
    for i in range(COL):
        sum+=pow(2,i)*arr[i]
    return sum
 
 
# The main function that prints
# all unique rows in a given matrix.
def findUniqueRows(M):
     
    b,root =BST(0),None
     
    #Traverse through the matrix
    for i in range(ROW):
        #insert the row into BST
        root = b.Insert(root,convert(M[i]))
     
    #print
    b.Inorder(root)
 
# Driver Code
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 shinjanpatra


Javascript




<script>
 
// Given a binary matrix of M X N of integers,
// you need to return only unique rows of binary array
var ROW = 4
var COL = 5
 
class 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.
            return new BST(value);
        }
         
        //if the value is present
        if(value == root.data)
         return root;
     
        // 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.
        return root;
    }
 
    // 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 decimal
function convert(arr)
{
    var sum=0;
     
    for(var i=0; i<COL; i++)
    {
        sum+=Math.pow(2,i)*arr[i];
    }
    return sum;
}
 
// print the column represented as integers
function print(p)
{
    for(var i=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.
function findUniqueRows(M)
{
     
    var b =new BST(0),root = null;
     
    //Traverse through the matrix
    for(var i=0; i<ROW; i++)
    {
        //insert the row into BST
        root=b.Insert(root,convert(M[i]));
    }
     
     
    //print
    b.Inorder(root);
     
}
 
// Driver Code
var 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 rutvik_56.
</script>


Output

1 0 1 0 0 
1 0 1 1 0 
0 1 0 0 1 

Complexity 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: 

  1. Create a Trie where rows can be stored.
  2. Traverse through the matrix and insert the row into the Trie.
  3. Trie cannot store duplicate entries so the duplicates will be removed
  4. 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>
using namespace std;
#define ROW 4
#define COL 5
 
// A Trie node
class Node
{
    public:
    bool isEndOfCol;
    Node *child[2]; // Only two children needed for 0 and 1
} ;
 
 
// A utility function to allocate memory
// for a new Trie node
Node* newNode()
{
    Node* temp = new 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)
        cout << M[row][i] << " ";
    cout << endl;
}
 
// 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 Code
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;
}
 
// This code is contributed by rathbhupendra


C




//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("\n");
}
 
// 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;
}


Java




// Java code to implement the approach
 
// Given a binary matrix of M X N of integers,
// you need to return only unique rows of binary array
import java.util.*;
 
class GFG {
  static class Node {
    boolean isEndOfCol;
    Node[] child = new Node[2]; // Only two children
    // needed for 0 and 1
  }
 
  static class Trie {
    // A utility function to allocate memory for a new
    // Trie node
    public static Node NewNode()
    {
      Node temp = new Node();
      temp.isEndOfCol = false;
      temp.child[0] = temp.child[1] = null;
      return temp;
    }
 
    // Inserts a new matrix row to Trie.
    // If row is already present, then returns false,
    // otherwise inserts the row and return true
    public static boolean Insert(Node root, int[][] M,
                                 int row, int col)
    {
      // base case
      if (root == null)
        root = NewNode();
 
      // Recur if there are more entries in this row
      if (col < M[0].length)
        return Insert(root.child[M[row][col]], M,
                      row, col + 1);
 
      else // If all entries of this row are processed
      {
        // unique row found, return true
        if (!(root.isEndOfCol))
          return root.isEndOfCol = true;
 
        // duplicate row found, return false
        return false;
      }
    }
 
    // A utility function to print a row
    public static void PrintRow(int[][] M, int row)
    {
      for (int i = 0; i < M[0].length; ++i)
        System.out.print(M[row][i] + " ");
      System.out.println();
    }
 
    // The main function that prints all unique rows in
    // a given matrix.
    public static void FindUniqueRows(int[][] M)
    {
      Node root = null; // create an empty Trie
 
      // Iterate through all rows
      for (int i = 0; i < M.length; ++i)
 
        // insert row to TRIE
        if (Insert(root, M, i, 0))
 
          // unique row found, print it
          PrintRow(M, i);
    }
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int[][] M = { { 0, 1, 0, 0, 1 },
                 { 1, 0, 1, 1, 0 },
                 { 0, 1, 0, 0, 1 },
                 { 1, 0, 1, 0, 0 } };
    Trie.FindUniqueRows(M);
 
    System.out.println();
  }
}
 
// This code is contributed by phasing17


Python3




class Node:
    def __init__(self):
        self.isEndOfCol = False
        self.child = [None, None]
 
def newNode():
    temp = Node()
    return temp
 
def insert(root, M, row, col):
    """Insert a row of binary values into the trie.
    If the row is already in the trie, return False.
    Otherwise, return True.
    """
    if root is None:
        root = newNode()
 
    if col < COL:
        return insert(root.child[M[row][col]], M, row, col+1)
    else:
        if not root.isEndOfCol:
            root.isEndOfCol = True
            return True
        return False
 
def printRow(row):
    # Print a row of binary values
    for i in row:
        print(i, end=" ")
    print()
 
def findUniqueRows(M):
    # Find and print unique rows in a matrix of binary values
    unique_rows = []
    for i in range(ROW):
        if not any(M[i] == row for row in unique_rows):
            unique_rows.append(M[i])
    for row in unique_rows:
        printRow(row)
# Number of rows and columns in the matrix
ROW = 4
COL = 5
 
# Example matrix of binary values
M = [[0, 1, 0, 0, 1],
     [1, 0, 1, 1, 0],
     [0, 1, 0, 0, 1],
     [1, 0, 1, 0, 0]]
 
# Find and print unique rows in the matrix
findUniqueRows(M)
 
# This code is contributed by Vikram_Shirsat


Javascript




// Given a binary matrix of M X N of integers,
// you need to return only unique rows of binary array
let ROW = 4
let COL = 5
 
// A Trie node
class Node
{
    constructor()
    {
        this.isEndOfCol;
        this.child = new Array(2); // Only two children needed for 0 and 1
    }
} ;
 
 
// A utility function to allocate memory
// for a new Trie node
function newNode()
{
    let temp = new Node();
    temp.isEndOfCol = 0;
    temp.child[0] = null;
    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
function insert(root, M, row, col)
{
    // base case
    if (root == null)
        root = newNode();
 
    // Recur if there are more entries in this row
    if (col < (M.length).length)
        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))
        {
            (root).isEndOfCol = 1;
            return 1;
        }
 
        // duplicate row found, return 0
    }
    return 0;
}
 
// A utility function to print a row
function printRow(M, row)
{
    console.log(M[row].join(" "))
}
 
// The main function that prints
// all unique rows in a given matrix.
function findUniqueRows(M)
{
    let root = null; // create an empty Trie
    let 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 Code
let 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 phasing17


C#




// Given a binary matrix of M X N of integers,
// you need to return only unique rows of binary array
 
using System;
 
namespace Trie
{
    class Node
    {
        public bool isEndOfCol;
        public Node[] child = new Node[2]; // Only two children needed for 0 and 1
    }
     
    class Trie
    {
        // A utility function to allocate memory
        // for a new Trie node
        public static Node NewNode()
        {
            Node temp = new Node();
            temp.isEndOfCol = false;
            temp.child[0] = temp.child[1] = null;
            return temp;
        }
     
        // Inserts a new matrix row to Trie.
        // If row is already present,
        // then returns false, otherwise inserts the row and
        // return true
        public static bool Insert(ref Node root, int[,] M,
                        int row, int col )
        {
            // base case
            if (root == null)
                root = NewNode();
     
            // Recur if there are more entries in this row
            if (col < M.GetLength(1))
                return Insert (ref root.child[M[row, col]], M, row, col + 1);
     
            else // If all entries of this row are processed
            {
                // unique row found, return true
                if (!(root.isEndOfCol))
                    return root.isEndOfCol = true;
     
                // duplicate row found, return false
                return false;
            }
        }
     
        // A utility function to print a row
        public static void PrintRow(int[,] M, int row)
        {
            for(int i = 0; i < M.GetLength(1); ++i)
                Console.Write(M[row, i] + " ");
            Console.WriteLine();
        }
     
        // The main function that prints
        // all unique rows in a given matrix.
        public static void FindUniqueRows(int[,] M)
        {
            Node root = null; // create an empty Trie
     
            // Iterate through all rows
            for (int i = 0; i < M.GetLength(0); ++i)
             
                // insert row to TRIE
                if (Insert(ref root, M, i, 0))
                 
                    // unique row found, print it
                    PrintRow(M, i);
        }
    }
     
    // Driver code
     
    class GFG
    {
        static void Main(string[] args)
        {
            int[,] M = {{0, 1, 0, 0, 1},
                       {1, 0, 1, 1, 0},
                       {0, 1, 0, 0, 1},
                       {1, 0, 1, 0, 0}};
     
            Trie.FindUniqueRows(M);
     
            Console.ReadLine();
        }
    }
}


Output

0 1 0 0 1 
1 0 1 1 0 
1 0 1 0 0 

Complexity 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: 

  1. Create a HashSet where rows can be stored as a String.
  2. Traverse through the matrix and insert the row as String into the HashSet.
  3. HashSet cannot store duplicate entries so the duplicates will be removed
  4. Traverse the HashSet and print the rows.

Implementation: 

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


Javascript




<script>
// Javascript code to print unique row in a
// given binary matrix
 
function printArray(arr,row,col)
{
    let set = new Set();
    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 code
let 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>


Output

01001
10110
11100

Complexity 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.


Similar Reads

Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
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 a
6 min read
Count of unique rows in a given Matrix
Given a 2D matrix arr of size N*M containing lowercase English letters, the task is to find the number of unique rows in the given matrix. Examples: Input: arr[][]= { {'a', 'b', 'c', 'd'}, {'a', 'e', 'f', 'r'}, {'a', 'b', 'c', 'd'}, {'z', 'c', 'e', 'f'} }Output: 2Explanation: The 2nd and the 4th row are unique. Input: arr[][]={{'a', 'c'}, {'b', 'd'
10 min read
Print all unique paths from given source to destination in a Matrix moving only down or right
Given a 2-D array mat[][], a source ‘s’ and a destination ‘d’, print all unique paths from given ‘s’ to ‘d’. From each cell, you can either move only to the right or down. Examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}}, s[] = {0, 0}, d[]={1, 2}Output: 1 4 5 61 2 5 61 2 3 6 Input: mat[][] = {{1, 2}, {3, 4}}, s[] = {0, 1}, d[] = {1, 1}Output: 2 4
6 min read
Minimum swaps needed to convert given Binary Matrix A to Binary Matrix B
Given two binary matrices, A[][] and B[][] of size N×M, the task is to find the minimum number of swaps of the elements of matrix A, needed to convert matrix A into matrix B. If it is impossible to do so then print "-1". Examples : Input: A[][] = {{1, 1, 0}, {0, 0, 1}, {0, 1, 0}}, B[][] = {{0, 0, 1}, {0, 1, 0}, {1, 1, 0}}Output: 3Explanation: One p
8 min read
Python Counter| Find duplicate rows in a binary matrix
Given a binary matrix whose elements are only 0 and 1, we need to print the rows which are duplicate of rows which are already present in the matrix. Examples: Input : [[1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 1]] Output : (1, 1, 0, 1, 0, 1) (0, 0, 1, 0, 0, 1) We have existi
2 min read
Check if all rows of a Binary Matrix have all ones placed adjacently or not
Given a binary matrix mat[][] of dimension N*M, the task is to check if all 1s in each row are placed adjacently on the given matrix. If all 1s in each row are adjacent, then print "Yes". Otherwise, print "No". Examples: Input: mat[][] = {{0, 1, 1, 0}, {1, 1, 0, 0}, {0, 0, 0, 1}, {1, 1, 1, 0}Output: YesExplanation:Elements in the first row are {0,
9 min read
Find pair of rows in a binary matrix that has maximum bit difference
Given a Binary Matrix. The task is to find the pair of row in the Binary matrix that has maximum bit difference Examples: Input: mat[][] = {{1, 1, 1, 1}, {1, 1, 0, 1}, {0, 0, 0, 0}}; Output : (1, 3) Bit difference between row numbers 1 and 3 is maximum with value 4. Bit difference between 1 and 2 is 1 and between 2 and 3 is 3. Input: mat[][] = {{1
15 min read
Find duplicate rows in a binary matrix
Given a binary matrix whose elements are only 0 and 1, we need to print the rows which are duplicates of rows that are already present in the matrix. Examples: Input : {1, 1, 0, 1, 0, 1}, {0, 0, 1, 0, 0, 1}, {1, 0, 1, 1, 0, 0}, {1, 1, 0, 1, 0, 1}, {0, 0, 1, 0, 0, 1}, {0, 0, 1, 0, 0, 1}.Output :There is a duplicate row at position: 4 There is a dupl
15+ min read
Minimum count of rows between rows containing X and Y respectively
Given a Grid of size NxM, and two integers X and Y, the task is to count the minimum number of rows between the row containing X and the row containing Y in such a way that the adjacent rows in between them have at least one element in common. Multiple occurrences of a number are allowed in the grid. In other words, two rows are said to be adjacent
14 min read
Unique cells in a binary matrix
Given a matrix of size n × m consisting of 0's and 1's. We need to find the number of unique cells with value 1 such that the corresponding entire row and the entire column do not have another 1. Return the number of unique cells. Examples: Input : mat[][] = {0, 1, 0, 0 0, 0, 1, 0 1, 0, 0, 1} Answer : 2 The two 1s that are unique in their rows and
11 min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Minimize cost to convert a given matrix to another by flipping columns and reordering rows
Given two binary matrices mat[][] and target[][] of dimensions N * M, the task is to find the minimum cost to convert the matrix mat[][] into target[][] using the following operations: Flip a particular column in mat[][] such that all 1s become 0s and vice-versa. The cost of this operation is 1.Reorder the rows of mat[][]. The cost of this operatio
10 min read
Maximize minimum of array generated by maximums of same indexed elements of two rows of a given Matrix
Given a matrix mat[][] of N rows and M columns, the task is to choose any two rows(i, j) (0 ? i, j ? N - 1) and construct a new array A[] of size M, where A[k] = max(mat[i][k], mat[j][k]) such that minimum of A[] is maximum possible. Examples: Input: mat[][] = {{5, 0, 3, 1, 2}, {1, 8, 9, 1, 3}, {1, 2, 3, 4, 5}, {9, 1, 0, 3, 7}, {2, 3, 0, 6, 3}, {6,
7 min read
Queries to count sum of rows and columns of a Matrix present in given ranges
Given a matrix A[][] of size N * M and a 2D array queries[][] consisting of Q queries of the form {L, R}, the task is to count the number of row-sums and column-sums which are an integer from the range [L, R]. Examples: Input: N = 2, M = 2, A[][] = {{1, 4}, {2, 5}}, Q = 2, queries[][] = {{3, 7}, {3, 9}}Output: 3 4Explanation:Sum of the first row =
14 min read
Length of largest common subarray in all the rows of given Matrix
Given a matrix mat[][] of size N×M where each row of the matrix is a permutation of the elements from [1, M], the task is to find the maximum length of the subarray present in each row of the matrix. Examples: Input: mat[][] = {{1, 2, 3, 4, 5}, {2, 3, 4, 1, 5}, {5, 2, 3, 4, 1}, {1, 5, 2, 3, 4}}Output: 3Explanation: In each row, {2, 3, 4} is the lon
10 min read
Count the number of rows and columns in given Matrix having all primes
Given a 2D matrix arr[] of size N*M, the task is to find the number of rows and columns having all primes. Examples: Input: arr[]= { { 2, 5, 7 }, { 3, 10, 4 }, { 11, 13, 17 } };Output: 3Explanation: 2 Rows: {2, 5, 7}, {11, 13, 17}1 Column: {2, 3, 11} Input: arr[]={ { 1, 4 }, { 4, 6 } }Output: 0 Approach: Follow the below steps to solve this problem
7 min read
Count of palindromic rows in given Matrix
Given a matrix arr[][] of size N * N, the task is to find the number of palindromic rows. Examples: Input: arr[][] = {{1, 3, 1}, {2, 2, 3}, {2, 1, 2}} Output: 2Explanation: First and third row forms a palindrome i.e 1 3 1 and 2 1 2. Therefore, count of palindromic rows is 2. Input: arr[][] = {{2, 2, 3, 2}, {1, 3, 3, 1}, {4, 2, 2, 4}, {5, 6, 6, 5}}
4 min read
Minimum sum of all absolute differences of same column elements in adjacent rows in a given Matrix
Given a matrix mat[][] having N rows and M columns, the task is to find the minimum distance between two adjacent rows where the distance between two rows is defined as the sum of all absolute differences between two elements present at the same column in the two rows. Examples: Input: mat[][] = {{1, 4, 7, 10}, {2, 5, 8, 11}, {6, 9, 3, 12}}Output:
5 min read
Count of empty cells in given square Matrix after updating the rows and columns for Q queries
Given a binary matrix of size NxN which is initially filled with 0's and Q queries such that: Each query is of type (r, c) where r and c denotes the row number and column number respectively.Change all the 0's of rth row and cth column to 1. The task is to find the count of 0's after performing each query in the given matrix. Examples: Input: N = 3
9 min read
Find a common element in all rows of a given row-wise sorted matrix
Given a matrix where every row is sorted in increasing order. Write a function that finds and returns a common element in all rows. If there is no common element, then returns -1. Example: Input: mat[4][5] = { {1, 2, 3, 4, 5}, {2, 4, 5, 8, 10}, {3, 5, 7, 9, 11}, {1, 3, 5, 7, 9}, }; Output: 5 A O(m*n*n) simple solution is to take every element of fi
15+ min read
Common elements in all rows of a given matrix
Given an m x n matrix, find all common elements present in all rows in O(mn) time and one traversal of matrix. Example: Input: mat[4][5] = {{1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, }; Output: 1 8 or 8 1 8 and 1 are present in all rows. A simple solution is to consider every element and check if it is present in all rows.
7 min read
Find all permuted rows of a given row in a matrix
We are given an m*n matrix of positive integers and a row number. The task is to find all rows in given matrix which are permutations of given row elements. It is also given that values in every row are distinct. Examples: Input : mat[][] = {{3, 1, 4, 2}, {1, 6, 9, 3}, {1, 2, 3, 4}, {4, 3, 2, 1}} row = 3 Output: 0, 2 Rows at indexes 0 and 2 are per
10 min read
Print all Unique Strings present in a given Array
Given an array of strings arr[], the task is to print all unique strings that are present in the given array. Examples: Input: arr[] = { "geeks", "geek", "ab", "geek" "code", "karega" } Output: geeks ab code karega Explanation: The frequency of the string "geeks" is 1. The frequency of the string "geek" is 2. The frequency of the string "ab" is 1.
15+ min read
Print all Distinct ( Unique ) Elements in given Array
Given an integer array, print all distinct elements in an array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: 12, 10, 9, 45, 2 Input: arr[] = {1, 2, 3, 4, 5}Output: 1, 2, 3, 4, 5 Input: arr[] = {1, 1, 1, 1, 1}
13 min read
Count of all unique paths from given source to destination in a Matrix
Given a 2D matrix of size n*m, a source ‘s’ and a destination ‘d’, print the count of all unique paths from given ‘s’ to ‘d’. From each cell, you can either move only to the right or down. Examples: Input: arr[][] = { {1, 2, 3}, {4, 5, 6} }, s = {0, 0}, d = {1, 2}Output: 3Explanation: All possible paths from source to destination are: 1 -&gt; 4 -
4 min read
Find the row with maximum unique elements in given Matrix
Given a matrix arr[][] of size N*M The task is to find the index of the row that has the maximum unique elements. If there are multiple rows possible, return the minimum indexed row. Examples: Input: arr[][] = { {1, 2, 3, 4, 5}, {1, 2, 2, 4, 7}, {1, 3, 1, 3, 1} } Output: 0Explanation: Rows 0, 1 &amp; 2 have 5, 4 &amp; 2 unique elements respectively
5 min read
Maximum count of unique index 10 or 01 substrings in given Binary string
Given a binary string str of length N, the task is to count the maximum number of adjacent pairs of form "01" or "10" that can be formed from the given binary string when one character can be considered for only one pair. Note: Adjacent pair means pair formed using adjacent characters. Examples: Input: str = "0101110"Output: 3Explanation: The three
5 min read
Second unique smallest value of given Binary Tree whose each node is minimum of its children
Given a full binary tree where each node value is the same as the minimum value between its children, the task is to find the second minimum unique value of the tree. Examples: Input: tree: Output: 5Explanation: All the unique values present in the tree are 2, 5 and 7.The second smallest is 5. Input: tree: Output: -1Explanation: All the numbers pre
15+ min read