Find Smallest Common Element in All Rows Problem
Description
LeetCode Problem 1198.
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.
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
Approach: Counting
Each row is strictly increasing, so a value appears at most once per row. That means a value is in every row exactly when it appears m times in the whole matrix.
Values are at most 10^4, so a plain array count of size 10001 works. Read the rows from top to bottom, each one left to right, and add one to count[x] for every value. The moment some count reaches m, return that value.
Why is the first value to reach m the smallest common one? A count can reach m only while we read the last row, since each earlier row adds at most one. The last row is read in increasing order, so the first common value we meet there is the smallest one. If no count reaches m, there is no common element: return -1.
Complexity: O(m · n) time and O(104) extra space for the counts.
class Solution:
def smallestCommonElement(self, mat: List[List[int]]) -> int:
count = [0] * 10001 # values are at most 10^4
for row in mat:
for x in row:
count[x] += 1 # rows are strictly increasing: once per row at most
if count[x] == len(mat):
# Only possible in the last row, which we read in increasing order.
return x
return -1