Matrix: Get the common elements in all row of a matrix.

Problem Statement:

You are given an m*n matrix, you need to print all the common elements present in all the rows.

Example:

mat[4][5] = {{1, 2, 1, 8},
             {3, 7, 8, 5},
             {8, 7, 7, 3},
             {8, 1, 2, 7},
            };

Output: 8

Solution

In this solution we will use MAPS.

Initially insert all the elements of the first row in a map.
Then for each element for the remaining rows, check if the element is present in the map.
If it is present and is not a duplicate in current row, increment the count.
else we ignore the element.
Then once we traverse the last low, print the element if it has appeared m-1 times.

Solution in C++:

#include <vector>    
#include <algorithm>  
//visit www.ProDeveloperTutorial.com for 450+ solved questions  
#include <iostream>    
#include <unordered_map>

using namespace std;

#define r  4
#define c  5 

void print_common_elements(int arr[4][5]) 
{ 
    unordered_map<int, int> map; 
  
    // insert the element of the first row and initialize with value 1
    for (int j = 0; j < c; j++) 
        map[arr[0][j]] = 1; 
  
    for (int i = 1; i < r; i++) 
    { 
        for (int j = 0; j < c; j++) 
        { 
            // If element is present in the map and  is not duplicated in current row. 
            if (map[arr[i][j]] == i) 
            { 
               // increment count of the element in map by 1 
                map[arr[i][j]] = i + 1; 
  
                // If this is last row 
                if (i==r-1) 
                  cout << arr[i][j] << " "; 
            } 
        } 
    } 
} 

int main() 
{ 
    int arr[4][5] =
    {
        { 2, 4, 3, 8, 7 },
        { 4, 7, 1, 3, 6 },
        { 3, 5, 2, 1, 3 },
        { 4, 5, 0, 2, 3 },
    };
    cout << "The common elements in all the rows are ";
    print_common_elements(arr); 
    return 0; 
} 

Output:

The common elements in all the rows are 3
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *