Find Smallest Common Element in All Rows — LeetCode 1198 Python Solution
MediumLeetCode PremiumArrayHash TableBinary SearchCountingMatrix
- Problem
- #1198
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
- Output
- 5
Python solution
Python
class Solution:
def smallestCommonElement(self, mat: List[List[int]]) -> int:
cnt = Counter()
for row in mat:
for x in row:
cnt[x] += 1
if cnt[x] == len(mat):
return x
return -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(10^4) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1198. Find Smallest Common Element in All Rows is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1198. Find Smallest Common Element in All Rows?
- LeetCode 1198. Find Smallest Common Element in All Rows is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1198. Find Smallest Common Element in All Rows?
- The Python solution on this page runs in O(m \times n).
- What is the space complexity of LeetCode 1198. Find Smallest Common Element in All Rows?
- The Python solution on this page uses O(10^4) auxiliary space.
- What topics does LeetCode 1198. Find Smallest Common Element in All Rows cover?
- LeetCode 1198. Find Smallest Common Element in All Rows is tagged Array, Hash Table, Binary Search, Counting and Matrix on LeetCode.
- Is LeetCode 1198. Find Smallest Common Element in All Rows a premium problem?
- Yes. LeetCode 1198. Find Smallest Common Element in All Rows is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.