> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Find Smallest Common Element in All Rows

> Tested Python solution for LeetCode 1198 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 1198, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table), [Binary Search](/catalog/topics/binary-search), [Counting](/catalog/topics/counting), [Matrix](/catalog/topics/matrix). [View on LeetCode](https://leetcode.com/problems/find-smallest-common-element-in-all-rows/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1198   # by problem number
lcpy gen -s find_smallest_common_element_in_all_rows   # by problem name
```

## 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

```
Input: mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
Output: 5
```

```
Input: mat = [[1,2,3],[2,3,4],[2,3,5]]
Output: 2
```

### Constraints

* m == mat.length
* n == mat\[i].length
* 1 \<= m, n \<= 500
* 1 \<= mat\[i]\[j] \<= 10^4
* mat\[i] is sorted in strictly increasing order.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_smallest_common_element_in_all_rows/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_smallest_common_element_in_all_rows/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(m * n)
    # Space: O(m * n)
    def smallest_common_element(self, mat: list[list[int]]) -> int:
        counts: dict[int, int] = {}
        for row in mat:
            for x in row:
                count = counts.get(x, 0) + 1
                if count == len(mat):
                    return x
                counts[x] = count
        return -1
```

## Complexity

| Time | Space |
| - | - |
| O(m \* n) | O(m \* n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.