NeetCode #26LC-1198MediumArrays & HashingNC Algo100
← Back to All Problems#26 · #1198 · Find Smallest Common Element in All Rows(找出所有行中最小的公共元素)
📌 Problem Statement & Constraints
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. Constraints: 1 <= m, n <= 500, 1 <= mat[i][j] <= 10^4, each row is strictly increasing.💡 Core Algorithmic Approaches
- A value is common to all rows only if it appears in every row. Count, for each value, how many rows contain it.
- Use a hash map from value to the number of rows containing it. Iterate each row and add 1 per distinct value in that row (the rows are strictly increasing, so no value repeats within a row).
- Then find the smallest value whose row count equals
m. - Because the rows are sorted, an alternative is a k-way merge with a heap or a pointer per row, but the counting approach is simpler and O(m * n).
💻 Benchmark Python3 Implementation
class Solution:
def smallestCommonElement(self, mat: List[List[int]]) -> int:
from collections import defaultdict
rows = len(mat)
cnt = defaultdict(int)
for row in mat:
for v in row: # strictly increasing -> no duplicates
cnt[v] += 1
best = -1
for v in sorted(cnt): # ascending order -> first hit is the answer
if cnt[v] == rows:
best = v
break
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(m * n + V log V): the counting pass is O(m * n) and sorting the distinct values is O(V log V) with V <= 10^4. A k-way merge would be O(m * n * log m).
💾 Space Complexity
O(V) for the counter, V <= 10^4.
⚠️ Interview Pitfalls & Follow-ups
- Counting occurrences rather than rows: within a row, each value appears once (strictly increasing), so the distinction does not bite here -- but if rows could contain duplicates, you would need to deduplicate per row.
- Iterating
cntin insertion order and taking the first match: the first match in insertion order is not necessarily the smallest value. Sort the keys. - Assuming the answer must be in the first row's first element: it can be any value.
- Using a set intersection of all rows: correct and concise, but it loses the count information and is O(m * n) with a larger constant.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
找出所有行中最小的公共元素
给你一个 m × n 的矩阵 mat,其中每一行都按 非递减 顺序排列。请你找出同时出现在 所有行 中的最小元素。如果不存在这样的元素,返回 -1。约束:1 ≤ m, n ≤ 500;1 ≤ mat[i][j] ≤ 10^4;每行按非递减顺序排列。
核心要点
- 二分查找(标准解) :遍历第一行中的每个元素 v(第一行已升序,因此找到的第一个满足条件的 v 即为最小),对其他每一行用二分查找判断 v 是否存在。
- 为什么以第一行为候选集 :公共元素必然出现在第一行中,因此只需在第一行的元素里找,候选规模从 m × n 降到 n。
- 复杂度 :第一行 n 个候选,每个候选对 m-1 行做二分(每行 O(log n)),总计 O(n · m · log n)。
- 更优方案 · 逐行缩小候选 :维护一个候选集合,初始为第一行元素,逐行与当前行的元素求交集。当候选集为空时提前返回 -1。若每行用哈希集合,总复杂度 O(m · n)。
常见陷阱
- 对每一行都从头线性查找 :忽略「行已升序」这一条件,退化为 O(m · n · n)。二分查找才是本题利用有序性的关键。
- 遍历整个第一行而不提前返回 :第一行升序,因此 第一个 满足「存在于所有行」的元素就是全局最小,必须立即返回,不能继续找更大的。
- 二分时漏判「找不到」 : bisect_left 返回插入位置,必须同时检查 p < len(row) 且 row[p] == v ,否则会把「插入位置恰好等于 v 的下一位」误判为存在。
- 方案二忘记候选集为空时提前退出 :不退出会白跑完剩余所有行。
参考实现
import bisect
class Solution:
def smallestCommonElement(self, mat: list[list[int]]) -> int:
# 方案一:以第一行为候选,逐行二分(利用行有序)
first = mat[0]
for v in first: # 第一行升序 -> 首个满足者即最小
ok = True
for row in mat[1:]:
p = bisect.bisect_left(row, v)
if p == len(row) or row[p] != v:
ok = False
break
if ok:
return v
return -1
# 方案二:候选集逐行求交(O(m*n),行无序也适用)
# cand = set(mat[0])
# for row in mat[1:]:
# cand &= set(row)
# if not cand: return -1
# return min(cand)