Lucky Numbers in a Matrix - Problem
Given an m ร n matrix of distinct numbers, your task is to find all the "lucky numbers" in the matrix.
A lucky number is a special element that satisfies both conditions:
- It is the minimum element in its row
- It is the maximum element in its column
Think of it as finding the "sweet spot" - numbers that are simultaneously the smallest in their horizontal neighborhood and the largest in their vertical neighborhood!
Example:
Matrix: [[3,7,8],
[9,11,13],
[15,16,17]]
Lucky number: 15
- 15 is minimum in row [15,16,17]
- 15 is maximum in column [3,9,15]Return all lucky numbers in any order.
Input & Output
example_1.py โ Basic 3x3 Matrix
$
Input:
matrix = [[3,7,8],[9,11,13],[15,16,17]]
โบ
Output:
[15]
๐ก Note:
15 is the minimum in its row [15,16,17] and maximum in its column [3,9,15], making it the only lucky number.
example_2.py โ 4x4 Matrix with Single Lucky Number
$
Input:
matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
โบ
Output:
[12]
๐ก Note:
12 is minimum in its row [15,16,17,12] and maximum in its column [2,7,12].
example_3.py โ No Lucky Numbers
$
Input:
matrix = [[7,8],[1,2]]
โบ
Output:
[]
๐ก Note:
No element satisfies both conditions. 1 is row minimum but not column maximum, 7 is column maximum but not row minimum.
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 โค n, m โค 50
- 1 โค matrix[i][j] โค 105
- All elements in the matrix are distinct
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Challenge
We need elements that are minimum in their row AND maximum in their column
2
Brute Force Reality
Checking each element requires scanning entire rows and columns repeatedly
3
The Optimization
Pre-compute all row minimums and column maximums once
4
Smart Comparison
Each element only needs two comparisons instead of m+n comparisons
Key Takeaway
๐ฏ Key Insight: The two-pass optimization reduces time complexity from O(mยฒnยฒ) to O(mn) by eliminating redundant row and column scans. Since all elements are distinct, there can be at most one lucky number in the entire matrix.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code