← Oracle questions

Find common elements in all rows of a matrix

Filed under Oracle

Free read 3 of 3

Confirm if elements within the same row can be duplicated and whether output order matters.

The question

Given a 2D matrix, find all elements that appear in every row of the matrix, optimizing the solution to use no extra space where possible.

Constraints

  • 1 <= matrix.length, matrix[0].length <= 100
  • -1000 <= matrix[i][j] <= 1000

Examples

Input
matrix = [[1, 2, 3, 4], [2, 4, 5, 6], [7, 2, 4, 8]]
Output
[2, 4]
Why
2 and 4 are present in every row of the matrix.

Approach

  1. Confirm if elements within the same row can be duplicated and whether output order matters.

Solution

O(R * C) time, O(C) space

Python
class Solution:
    def commonElements(self, matrix: list[list[int]]) -> list[int]:
        if not matrix or not matrix[0]:
            return []
        common = set(matrix[0])
        for row in matrix[1:]:
            common.intersection_update(row)
        return list(common)

Tips

  • What they are testing: Test with duplicate elements in the same row, matrices with no common elements, and single-row matrices.
  • Common mistake: Not handling duplicate occurrences within a single row properly when using set intersections.

Follow-ups

  • Optimize solution without using extra space.

Related Oracle questions

Collected from public candidate posts and coding forums. Updated Nov 2026.