File: lucky-numbers-in-a-matrix/solution.py

Date: 2026-06-06

Time: 17:29

lucky-numbers-in-a-matrix/solution.py

Purpose

This file solves LeetCode 1380 — Lucky Numbers in a Matrix. A "lucky number" is an element that is simultaneously the minimum in its row and the maximum in its column. The file owns both the solution and its inline unit tests.

Key Components

dfs(matrix: List[List[int]]) -> List[int] — The solver function. Despite the name dfs, this performs no depth-first search; it's a brute-force scan over rows. The naming is a repo-wide convention (all solutions export a function called dfs) rather than a description of the algorithm.

Contract:

TestDfs — Seven unit tests covering the examples from the problem, plus edge cases for single-element, single-row, single-column, and corner-position lucky numbers.

Patterns

Dependencies

Imports: typing.List (type hint), unittest (inline tests).

Imported by: lucky-numbers-in-a-matrix/test_solution.py (and hundreds of other test files import from their respective solution.py — the "Imported By" list in the prompt is the cross-reference for the test runner, not actual imports of *this* file).

Flow

1. Iterate over each row in the matrix.

2. Compute min_val = min(row) — the row minimum.

3. Find col = row.index(min_val) — the column index of that minimum.

4. Check if minval is the column maximum by asserting matrix[r][col] <= minval for every row r.

5. If so, append min_val to the result list.

Invariants

Error Handling

None. Empty matrices would cause min() to raise ValueError, but the problem guarantees m, n >= 1. The function trusts its caller to provide valid input per the LeetCode contract.