Lucky Numbers in a Matrix - Problem

Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order.

A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.

Input & Output

Example 1 — Basic Case with Lucky Number
$ Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]
💡 Note: 15 is the minimum in row 2 [15,16,17] and maximum in column 0 [3,9,15], making it a lucky number
Example 2 — No Lucky Numbers
$ Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
Output: []
💡 Note: No element satisfies both conditions: being minimum in its row AND maximum in its column
Example 3 — Single Element Matrix
$ Input: matrix = [[7]]
Output: [7]
💡 Note: Single element is both minimum in its row and maximum in its column by definition

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 a Matrix INPUT m x n Matrix (3x3) 3 7 8 9 11 13 15 16 17 R0 R1 R2 C0 C1 C2 Input Matrix: [[3,7,8], [9,11,13],[15,16,17]] Lucky Number: Min in row AND Max in column All values are distinct ALGORITHM STEPS 1 Find Row Minimums For each row, find min value Row0: 3 Row1: 9 Row2: 15 2 Find Column Maximums For each col, find max value Col0: 15 Col1: 16 Col2: 17 3 Find Intersection Values in both sets 3,9,15 15,16,17 15 4 Return Lucky Numbers Intersection = [15] Time: O(m*n) | Space: O(m+n) Single pass for each dimension FINAL RESULT 3 7 8 9 11 13 15 16 17 Min in Row 2 Max in Col 0 LUCKY NUMBER! Output: [15] Verification: 15 = min(15,16,17) [OK] 15 = max(3,9,15) [OK] Key Insight: Instead of checking each element (O(m*n) per element), precompute all row minimums and column maximums first. A lucky number must appear in BOTH sets. Since all values are distinct, the intersection contains at most one element. This reduces complexity from O(m*n*(m+n)) to O(m*n). TutorialsPoint - Lucky Numbers in a Matrix | Optimized: Precompute Row Min and Column Max
Asked in
Amazon 25 Microsoft 18
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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