Python 1380.py
class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
width = len(matrix[0])
height = len(matrix)
# lucky column
col = []
for x in range(width):
col.append(max(m[x] for m in matrix))
for y in range(height):
# lucky row
lucky = min(matrix[y])
for x in range(width):
if matrix[y][x] == lucky and lucky == col[x]:
yield lucky
Difficulty
and has an acceptance rate of about 80% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Matrix
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a method that extracts “lucky numbers” from a two-dimensional integer array. A lucky number is defined as an element that is simultaneously the smallest value in its row and the largest value in its column. The method is written as a generator, yielding each lucky number as it is discovered rather than constructing an intermediate collection.
Key Steps
The algorithm proceeds in three logical phases: dimension extraction, column-wise maximum computation, and row-wise scanning for matches.
The first phase determines the matrix dimensions. The code assumes a non-empty matrix and accesses the first row to obtain the column count, while the total number of rows is derived from the outer list length.
width = len(matrix[0])
height = len(matrix)
The second phase builds a list that stores the maximum value for each column. This is achieved by iterating over column indices and applying a generator expression that extracts the element at the current column from every row. The resulting list, col, holds the column maxima in order.
col = []
for x in range(width):
col.append(max(m[x] for m in matrix))
The final phase walks through each row, computes the row’s minimum value, and then checks each column position to see whether the current element equals both the row minimum and the pre-computed column maximum. When a match is found, the element is yielded.
for y in range(height):
lucky = min(matrix[y])
for x in range(width):
if matrix[y][x] == lucky and lucky == col[x]:
yield lucky
Edge Cases Handled
The code naturally accommodates matrices with a single row or a single column. In a single-row matrix, the row minimum is also the only candidate for a lucky number, and the column maxima list contains the same values, allowing the generator to yield any element that satisfies the equality test. Conversely, in a single-column matrix, each row’s minimum is the sole element of that row, and the column maxima list contains the maximum of the entire column, so only the overall maximum can be yielded.
When all entries in the matrix are identical, every element is both the row minimum and the column maximum. The algorithm will yield each occurrence because the equality condition holds for every cell. Because the method yields values rather than returning a list, the caller can decide whether to collect duplicates or stop after the first result.
If the matrix contains rows of varying lengths, the initial dimension extraction (len(matrix[0])) would reference the length of the first row, and subsequent column maximum calculations would attempt to access indices that may be out of range for shorter rows. However, the code’s design presumes a well-formed rectangular matrix, and within that contract it correctly processes any rectangular shape, including degenerate cases such as a 1×1 matrix.
Performance Optimizations Observed
The implementation isolates the column maximum computation into a dedicated loop that runs once before any row scanning begins. By storing these maxima in the col list, the algorithm avoids recomputing column maxima for each row, reducing redundant work.
The use of generator expressions inside the max call (max(m[x] for m in matrix)) provides a memory-efficient way to traverse a column without constructing an intermediate list. This pattern is repeated for each column, yielding a compact representation of column data.
Yielding results directly from the inner loop eliminates the need for an auxiliary collection to hold all lucky numbers. This lazy evaluation means that memory consumption is proportional to the number of simultaneously active loop variables rather than the total number of lucky numbers, which can be advantageous for large matrices with few matches.
The row minimum is computed once per row (lucky = min(matrix[y])) and reused for all column checks within that row, preventing repeated scans of the same row. This single-pass approach for each row, combined with the pre-computed column maxima, ensures that each matrix element is examined at most twice: once during column maximum calculation and once during the row-wise comparison.
ELI5 - Simplified Explanation
Imagine a big grid full of numbers, kind of like a giant sheet of graph paper where every square has a secret number hiding inside. This code acts like a tiny detective looking for special spots.
The detective first goes through every column, which is like looking at all the numbers in a vertical stack. It picks the biggest number in each column and writes those special big numbers down on a notepad.
Next, the detective walks through every row, which is a horizontal line across the grid. This time, it looks for the smallest number in that row.
When the detective finds that smallest number, it checks if that same number happens to be one of the big numbers it already wrote on the notepad for that column. If the number is both the smallest in its row and the biggest in its column, the detective has found a lucky number. It shouts the number out loud as a prize whenever it discovers one of these hidden gems.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | JS | Java | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1370: Increasing Decreasing String
- problem 1310: XOR Queries of a Subarray
- problem 1328: Break a Palindrome
- problem 1343: Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality