Common elements in all rows of a given matrix
Pattern: Hashing and frequency
Track, for each value of the first row, how many rows in a row it has appeared in. Values that survive every row are the answer.
The problem
You are given a matrix with at least one row; rows may have different lengths. Return every value that appears in every
row, each value once, in increasing order. For example, for the rows [1, 2, 1, 4, 8], [3, 7, 8, 5, 1],
[8, 7, 7, 3, 1] and [8, 1, 2, 7, 9], the answer is [1, 8].
This problem is from Love Babbar's 450 sheet. Its main link points to GeeksforGeeks, which this site has not been able to
check automatically. The function name commonInAllRows and the sorted output are this guide's own.
Think first
- Which row limits the possible answers the most, before you look at any other row?
- For a candidate value, what single number tells you whether it is still alive after row
r? - A row can contain the same value twice. How do you avoid counting it twice for that row?
Hints
Brute force, and why it fails
For each value of the first row, search every other row for it: O(c × total size), where c is the first row's length.
Turning every row into a set and intersecting them is clean and also O(total size), at the cost of one set per row.
The key insight
A single map can track how many consecutive rows each candidate has survived. Requiring the count to equal the current row number both drops values that missed a row and ignores repeats inside a row.
Dry run
| rowsSeen | {1: 1, 2: 1, 4: 1, 8: 1} |
|---|
The rows are [1, 2, 1, 4, 8], [3, 7, 8, 5, 1], [8, 7, 7, 3, 1] and [8, 1, 2, 7, 9]. After row 0, the candidates 1, 2, 4 and 8 have each been seen in 1 row.
The plan
rowsSeen = {x: 1 for x in row 0}
for r from 1 to rows - 1:
for x in row r:
if rowsSeen[x] == r: # alive so far, first time in this row
rowsSeen[x] = r + 1
return sorted values x with rowsSeen[x] == rows
Complexity
- Time
O(T + c log c)- Space
O(c)
T is the total number of entries in the matrix, each looked at once. c is the length of the first row: the map holds
at most c values, and sorting the answers takes at most O(c log c).
Edge cases
- One row: every distinct value of that row, sorted.
- No common value: an empty list.
- Repeats inside a row, as in
[5, 5, 5], are counted once per row.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> commonInAllRows(int[][] matrix) {
Map<Integer, Integer> rowsSeen = new HashMap<>(); // value -> how many rows (so far) contain it
for (int x : matrix[0]) {
rowsSeen.put(x, 1);
}
for (int r = 1; r < matrix.length; r++) {
for (int x : matrix[r]) {
Integer count = rowsSeen.get(x);
if (count != null && count == r) { // seen in every earlier row, first time in this one
rowsSeen.put(x, r + 1);
}
}
}
List<Integer> result = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : rowsSeen.entrySet()) {
if (entry.getValue() == matrix.length) {
result.add(entry.getKey());
}
}
Collections.sort(result);
return result;
}
}C++
class Solution {
public:
vector<int> commonInAllRows(vector<vector<int>>& matrix) {
unordered_map<int, int> rowsSeen; // value -> how many rows (so far) contain it
for (int x : matrix[0]) {
rowsSeen[x] = 1;
}
int rows = static_cast<int>(matrix.size());
for (int r = 1; r < rows; r++) {
for (int x : matrix[r]) {
auto found = rowsSeen.find(x);
if (found != rowsSeen.end() && found->second == r) { // seen in every earlier row, first time in this one
found->second = r + 1;
}
}
}
vector<int> result;
for (auto& entry : rowsSeen) {
if (entry.second == rows) {
result.push_back(entry.first);
}
}
sort(result.begin(), result.end());
return result;
}
};Python
class Solution:
def commonInAllRows(self, matrix):
rows_seen = {x: 1 for x in matrix[0]} # value -> how many rows (so far) contain it
for r in range(1, len(matrix)):
for x in matrix[r]:
if rows_seen.get(x) == r: # seen in every earlier row, first time in this one
rows_seen[x] = r + 1
return sorted(x for x, count in rows_seen.items() if count == len(matrix))Common mistakes
- Increasing the count for every occurrence, so a value repeated in one row looks as if it were in several rows.
- Adding values from later rows as new candidates.
- Forgetting that a value that missed one row must never come back.