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
Lucky Numbers in MatrixOriginal Matrix37891113Row Mins & Col MaxsRow mins: [3, 9, 15]Col maxs: [15, 16, 17]Lucky: 15 โœ…๐Ÿ’ก Key InsightSince all numbers are distinct, there can beat most ONE lucky numberIf number X is min in row i and max in column j,no other number can satisfy both conditions!
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.
Asked in
Google 25 Amazon 18 Meta 12 Microsoft 8
34.6K Views
Medium Frequency
~15 min Avg. Time
980 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen