Find distinct elements common to all rows of a matrix

3.2

Given a n x n matrix. The problem is to find all the distinct elements common to all rows of the matrix. The elements can be printed in any order.

Examples:

Input : mat[][] = {  {2, 1, 4, 3},
                     {1, 2, 3, 2},  
                     {3, 6, 2, 3},  
                     {5, 2, 5, 3}  }
Output : 2 3

Input : mat[][] = {  {12, 1, 14, 3, 16},
                     {14, 2, 1, 3, 35},  
                     {14, 1, 14, 3, 11},  
                     {14, 25, 3, 2, 1},
                     {1, 18, 3, 21, 14}  }
Output : 1 3 14

Method 1: Using three nested loops. Check if an element of 1st row is present in all the subsequent rows. Time Complexity of O(n3). Extra space could be required to handle the duplicate elements.

 

Method 2: Sort all the rows of the matrix individually in increasing order. Then apply a modified approach of the problem of finding common elements in 3 sorted arrays. Below an implementation for the same is given.

C++

// C++ implementation to find distinct elements
// common to all rows of a matrix
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;

// function to individually sort
// each row in increasing order
void sortRows(int mat[][MAX], int n)
{
    for (int i=0; i<n; i++)
        sort(mat[i], mat[i] + n);
}

// function to find all the common elements
void findAndPrintCommonElements(int mat[][MAX], int n)
{
    // sort rows individually
    sortRows(mat, n);

    // current column index of each row is stored
    // from where the element is being searched in
    // that row
    int curr_index[n];
    memset(curr_index, 0, sizeof(curr_index));
    int f = 0;

    for (; curr_index[0]<n; curr_index[0]++)
    {
        // value present at the current column index
        // of 1st row
        int value = mat[0][curr_index[0]];

        bool present = true;

        // 'value' is being searched in all the
        // subsequent rows
        for (int i=1; i<n; i++)
        {
            // iterate through all the elements of
            // the row from its current column index
            // till an element greater than the 'value'
            // is found or the end of the row is
            // encountered
            while (curr_index[i] < n &&
                   mat[i][curr_index[i]] <= value)
                curr_index[i]++;

            // if the element was not present at the column
            // before to the 'curr_index' of the row
            if (mat[i][curr_index[i]-1] != value)
                present = false;

            // if all elements of the row have
            // been traversed
            if (curr_index[i] == n)
            {
                f = 1;
                break;
            }
        }

        // if the 'value' is common to all the rows
        if (present)
            cout << value << " ";

        // if any row have been completely traversed
        // then no more common elements can be found
        if (f == 1)
            break;
    }
}

// Driver program to test above
int main()
{
    int mat[][MAX] = {  {12, 1, 14, 3, 16},
        {14, 2, 1, 3, 35},
        {14, 1, 14, 3, 11},
        {14, 25, 3, 2, 1},
        {1, 18, 3, 21, 14}
    };

    int n = 5;
    findAndPrintCommonElements(mat, n);
    return 0;
}

Java

// JAVA Code to find distinct elements
// common to all rows of a matrix
import java.util.*;

class GFG {
    
    // function to individually sort
    // each row in increasing order
    public static void sortRows(int mat[][], int n)
    {
        for (int i=0; i<n; i++)
            Arrays.sort(mat[i]);
    }
     
    // function to find all the common elements
    public static void findAndPrintCommonElements(int mat[][],
                                                     int n)
    {
        // sort rows individually
        sortRows(mat, n);
     
        // current column index of each row is stored
        // from where the element is being searched in
        // that row
        int curr_index[] = new int[n];
        
        int f = 0;
     
        for (; curr_index[0]<n; curr_index[0]++)
        {
            // value present at the current column index
            // of 1st row
            int value = mat[0][curr_index[0]];
     
            boolean present = true;
     
            // 'value' is being searched in all the
            // subsequent rows
            for (int i=1; i<n; i++)
            {
                // iterate through all the elements of
                // the row from its current column index
                // till an element greater than the 'value'
                // is found or the end of the row is
                // encountered
                while (curr_index[i] < n &&
                       mat[i][curr_index[i]] <= value)
                    curr_index[i]++;
     
                // if the element was not present at the 
                // column before to the 'curr_index' of the 
               // row
                if (mat[i][curr_index[i]-1] != value)
                    present = false;
     
                // if all elements of the row have
                // been traversed
                if (curr_index[i] == n)
                {
                    f = 1;
                    break;
                }
            }
     
            // if the 'value' is common to all the rows
            if (present)
               System.out.print(value+" ");
     
            // if any row have been completely traversed
            // then no more common elements can be found
            if (f == 1)
                break;
        }
    }
    
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int mat[][] = {  {12, 1, 14, 3, 16},
                         {14, 2, 1, 3, 35},
                         {14, 1, 14, 3, 11},
                         {14, 25, 3, 2, 1},
                         {1, 18, 3, 21, 14}
                                            };
         
            int n = 5;
            findAndPrintCommonElements(mat, n);
    }
  }
// This code is contributed by Arnav Kr. Mandal.


Output:

1 3 14

Time Complexity: O(n2log n), each row of size n requires O(nlogn) for sorting and there are total n rows.
Auxiliary Space : O(n) to store current column indexes for each row.

 

Method 3: It uses the concept of hashing. The following steps are:

  1. Map the element of 1st row in a hash table. Let it be hash.
  2. Fow row = 2 to n
  3. Map each element of the current row into a temporary hash table. Let it be temp.
  4. Iterate through the elements of hash and check that the elements in hash are present in temp. If not present then delete those elements from hash.
  5. When all the rows are being processed in this manner, then the elements left in hash are the required common elements.
// C++ program to find distinct elements
// common to all rows of a matrix
#include <bits/stdc++.h>
using namespace std;

const int MAX = 100;

// function to individually sort
// each row in increasing order
void findAndPrintCommonElements(int mat[][MAX], int n)
{
    unordered_set<int> us;

    // map elements of first row
    // into 'us'
    for (int i=0; i<n; i++)
        us.insert(mat[0][i]);

    for (int i=1; i<n; i++)
    {
        unordered_set<int> temp;
        // mapping elements of current row
        // in 'temp'
        for (int j=0; j<n; j++)
            temp.insert(mat[i][j]);

        unordered_set<int>:: iterator itr;

        // iterate through all the elements
        // of 'us'
        for (itr=us.begin(); itr!=us.end(); itr++)

            // if an element of 'us' is not present
            // into 'temp', then erase that element
            // from 'us'
            if (temp.find(*itr) == temp.end())
                us.erase(*itr);

        // if size of 'us' becomes 0,
        // then there are no common elements
        if (us.size() == 0)
            break;
    }

    // print the common elements
    unordered_set<int>:: iterator itr;
    for (itr=us.begin(); itr!=us.end(); itr++)
        cout << *itr << " ";
}

// Driver program to test above
int main()
{
    int mat[][MAX] = { {2, 1, 4, 3},
                       {1, 2, 3, 2},
                       {3, 6, 2, 3},
                       {5, 2, 5, 3}  };
    int n = 4;
    findAndPrintCommonElements(mat, n);
    return 0;
}

Output:

3 2

Time Complexity: O(n2)
Space Complexity: O(n)

This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



3.2 Average Difficulty : 3.2/5.0
Based on 8 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.