Find Smallest Common Element in All Rows
MediumUpdated: Aug 2, 2025
Practice on:
Problem
Given an m x n matrix mat where every row is sorted in strictly increasing order, return the smallest common element in all rows.
If there is no common element, return -1.
Examples
Example 1:
Input: mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
Output: 5
Example 2:
Input: mat = [[1,2,3],[2,3,4],[2,3,5]]
Output: 2
Constraints:
m == mat.lengthn == mat[i].length1 <= m, n <= 5001 <= mat[i][j] <= 10^4mat[i]is sorted in strictly increasing order.
Solution
Method 1 – Counting Occurrences
Intuition
Since each row is sorted and contains only unique elements, we can count the occurrences of each number across all rows. The smallest number that appears in every row is the answer.
Approach
- Initialize a hash map (or array if values are bounded) to count occurrences of each number.
- For each row, increment the count for each number.
- After processing all rows, iterate through the keys in increasing order and return the first number whose count equals the number of rows.
- If no such number exists, return -1.
Code
C++
class Solution {
public:
int smallestCommonElement(vector<vector<int>>& mat) {
unordered_map<int, int> cnt;
int m = mat.size();
for (auto& row : mat) for (int x : row) cnt[x]++;
int ans = INT_MAX;
for (auto& [k, v] : cnt) if (v == m) ans = min(ans, k);
return ans == INT_MAX ? -1 : ans;
}
};
Go
func smallestCommonElement(mat [][]int) int {
cnt := map[int]int{}
m := len(mat)
for _, row := range mat {
for _, x := range row {
cnt[x]++
}
}
ans := 1<<31 - 1
for k, v := range cnt {
if v == m && k < ans {
ans = k
}
}
if ans == 1<<31-1 {
return -1
}
return ans
}
Java
class Solution {
public int smallestCommonElement(int[][] mat) {
Map<Integer, Integer> cnt = new HashMap<>();
int m = mat.length;
for (int[] row : mat) for (int x : row) cnt.put(x, cnt.getOrDefault(x, 0) + 1);
int ans = Integer.MAX_VALUE;
for (var e : cnt.entrySet()) if (e.getValue() == m) ans = Math.min(ans, e.getKey());
return ans == Integer.MAX_VALUE ? -1 : ans;
}
}
Kotlin
class Solution {
fun smallestCommonElement(mat: Array<IntArray>): Int {
val cnt = mutableMapOf<Int, Int>()
val m = mat.size
for (row in mat) for (x in row) cnt[x] = cnt.getOrDefault(x, 0) + 1
return cnt.filter { it.value == m }.keys.minOrNull() ?: -1
}
}
Python
class Solution:
def smallestCommonElement(self, mat: list[list[int]]) -> int:
from collections import Counter
m = len(mat)
cnt = Counter()
for row in mat:
cnt.update(row)
for x in sorted(cnt):
if cnt[x] == m:
return x
return -1
Rust
impl Solution {
pub fn smallest_common_element(mat: Vec<Vec<i32>>) -> i32 {
use std::collections::HashMap;
let m = mat.len();
let mut cnt = HashMap::new();
for row in &mat {
for &x in row {
*cnt.entry(x).or_insert(0) += 1;
}
}
let mut ans = i32::MAX;
for (&k, &v) in &cnt {
if v == m && k < ans {
ans = k;
}
}
if ans == i32::MAX { -1 } else { ans }
}
}
TypeScript
class Solution {
smallestCommonElement(mat: number[][]): number {
const cnt: Record<number, number> = {};
const m = mat.length;
for (const row of mat) for (const x of row) cnt[x] = (cnt[x] ?? 0) + 1;
let ans = Infinity;
for (const k in cnt) if (cnt[k] === m && +k < ans) ans = +k;
return ans === Infinity ? -1 : ans;
}
}
Complexity
- ⏰ Time complexity:
O(mn), wheremis the number of rows andnis the number of columns, since we scan all elements. - 🧺 Space complexity:
O(n), for the count map (number of unique elements).