VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-distinct-elements-common-rows-matrix/

⇱ Count Distinct Elements Common to All Rows - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Distinct Elements Common to All Rows

Last Updated : 22 Nov, 2025

Given a square matrix mat[][], find the number of distinct elements that are common to every row of the matrix.

Examples:

Input: mat[][] =   [[2, 1, 4, 3],
    [1, 2, 3, 2],
  [3, 6, 2, 3],
   [5, 2, 5, 3]]
Output: 2
Explanation: Elements common to all rows = [2, 3], count = 2

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: 3
Explanation: Elements common to all rows = [1, 3, 14], count = 3

[Naive Approach] Brute Force Row Checking - O(n^3) Time and O(n) Space

We can go through the first row, but only consider each distinct element from it. For every such element, we check whether it is present in all other rows by scanning each row one by one. If an element from the first row is found in every row, then it is a common element, so you increase your count.


Output
2

[Better Approach] Row-Wise Frequency Counting - O(n^2 * log(n)) Time and O(n^2) Space

A more efficient method is to count how many rows each distinct element appears in. Instead of checking every element of the first row against all other rows, we process each row independently and record its unique elements using a temporary set. For every distinct value in a row, we increment its frequency in a global map that tracks how many rows contain that value. After all rows are processed, any element whose frequency equals the total number of rows must be present in every row. The final answer is the count of such elements.


Output
2

[Expected Approach] Using One HashMap - O(n^2) Time and O(n) Space

Instead of using a set for every row, we use a single frequency map. We first put all elements of the first row in the map with frequency 1. Then for each new row, we check every element: if it already exists in the map and its frequency matches the current row index, we increase it. This way, an element’s frequency increases only if it appears in every row in order. At the end, the elements whose frequency becomes n are the ones present in all rows.


Output
2


Comment
Article Tags: