Problem
Given an n x n matrix, find all the distinct elements common to all rows of the matrix. The elements can be printed in any order.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= n <= 1000
- Matrix elements are integers (may be negative or positive)
Solution
Method 1 – Brute Force (Three Nested Loops)
Intuition
Check every element in the first row and see if it appears in every other row. If so, and it hasn’t already been added, include it in the answer.
Approach
- For each element in the first row:
- For each subsequent row, check if the element is present.
- If it is present in all rows and not already in the answer, add it.
- Return the answer list.
Code
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^3)
, since for each element in the first row, we may scan all rows and all columns. - 🧺 Space complexity:
O(n)
, for the answer list.
Method 2 – Hash Set Intersection
Intuition
Use a hash set to keep track of elements common to all rows. Intersect the set with each row to efficiently filter out non-common elements.
Approach
- Initialize a set with all elements from the first row.
- For each subsequent row, create a set of its elements and intersect it with the running set.
- After all rows, the set contains the common elements.
- Return the set as a list.
Code
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
, since each row is scanned and set operations are O(1) per element. - 🧺 Space complexity:
O(n)
, for the sets.