Find common elements in all rows of a matrix
Filed under Oracle
Free read 3 of 3Confirm 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
Confirm if elements within the same row can be duplicated and whether output order matters.
Use hash sets for each row and find the intersection across all sets.
Use the first row as a reference, check each element's presence in subsequent rows, and modify elements in place or use bit manipulation to avoid extra space.
Matrix with 1 row, or no common elements across rows.
Solution
O(R * C) time, O(C) space
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.