Given an M × N matrix, find all common elements present in every row.

For example,

Input: M × N matrix
 
[  7   1   3   5   3   6  ]
[  2   3   6   1   1   6  ]
[  6   1   7   2   1   4  ]
[  6   6   7   1   3   3  ]
[  5   5   6   1   5   4  ]
[  3   5   6   2   7   1  ]
[  4   1   4   3   6   4  ]
[  4   6   1   7   4   3  ]
 
Output: The common elements are 1 and 6

Practice this problem

The idea is simple and efficient – create an empty map and insert all the first row elements into the map with their value set as 1. For each element of the remaining rows, check if it is present on the map or not. If the element is present on the map, check its count to see if it is present in all previous rows or not. If yes, increment its count by 1; otherwise, ignore the element.

Following is the implementation in C++, Java, and Python based on the above idea. One particular case we need to handle that any duplicate entry in the same row should not get inserted into the map again.

C++


Download  Run Code

Output:

The common elements are: 6 1

Java


Download  Run Code

Output:

The common elements are: 6 1

Python


Download  Run Code

Output:

The common elements are: [1, 6]

The time complexity of the proposed solution is O(M × N) for an M × N matrix and doesn’t require any extra space.