MediumNo. 1198LeetCode Premium
Find Smallest Common Element in All Rows — LeetCode 1198 Python Solution
- Pattern
- Matrix and Grid
- Topics
- Array, Hash Table, Binary Search, Counting, Matrix
- 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
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
- Time
- O(m × n)
- Space · auxiliary
- O(104)
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
| No. | Problem | Difficulty |
|---|---|---|
| 1782 | Count Pairs Of Nodes | Hard |
| 2713 | Maximum Strictly Increasing Cells in a Matrix | Hard |
| 2856 | Minimum Array Length After Pair Removals | Medium |
| 0036 | Valid Sudoku | Medium |
| 0037 | Sudoku Solver | Hard |
| 0073 | Set Matrix Zeroes | Medium |
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 × n).
- What is the space complexity of LeetCode 1198. Find Smallest Common Element in All Rows?
The Python solution on this page uses O(104) 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.