VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-common-element-rows-row-wise-sorted-matrix/

⇱ Common element in all rows of a row-wise sorted matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Common element in all rows of a row-wise sorted matrix

Last Updated : 24 Nov, 2025

Given a matrix mat[][], where every row is sorted in increasing order, find any one element that is common to all rows. If no such element exists, return -1.

Examples:

Input: mat[][] = [[1, 2, 3, 4, 5],
[2, 4, 5, 8, 10],
[3, 5, 7, 9, 11],
[1, 3, 5, 7, 9]]
Output: 5
Explanation: The element 5 is present in every row, so it is returned.

Input: mat[][] = [[1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]]
Output: -1
Explanation: There is no element that appears in all rows, so the answer is -1.

[Naive Approach] Counting the Occurrences - O(m*n*m) Time and O(1) Space

We take each element from the first row and check whether this element appears in every other row. For every candidate element, we scan the entire row to see if it exists there or not. If an element from the first row is found in all rows, we return it as the common element. If none of the elements from the first row satisfy this condition, we return -1.


Output
5

[Better Approach] Using Hash Table- O(n * m) Time and O(n * m) Space

Since every row in the matrix is sorted, all duplicates in a row appear together. We use this fact by scanning each row only once and counting each distinct element using a hash map.

For each row:

  • We increment the frequency of the first element.
  • For every next element, we only increase its frequency if it is different from the previous one, ensuring that duplicates are not counted multiple times within the same row.

After processing all rows, any element whose frequency becomes equal to the number of rows must have appeared in every row, and thus it is a common element.

If no such element exists, we return -1.


Output
5

[Expected Approach] Pointer Based Approach - O(n * m) Time and O(n) Space

Since every row is already sorted, we use a multi-pointer technique to find a common element.

We place one pointer at the first column of each row. At each step, we compare the values pointed to:

  • If all pointers point to the same value, that value is the common element.
  • Otherwise, we find the maximum among the pointed values.
  • We move forward (right) the pointer of every row whose value is smaller than this maximum, because only the smaller values need to catch up to the largest one.

If any pointer moves beyond the last column, then no common element exists.


Output
5


Comment
Article Tags:
Article Tags: