Lucky Numbers in a Matrix Problem
Description
LeetCode Problem 1380.
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.
Example 1:
Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]
Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column.
Example 2:
Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
Output: [12]
Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
Example 3:
Input: matrix = [[7,8],[1,2]]
Output: [7]
Explanation: 7 is the only lucky number since it is the minimum in its row and the maximum in its column.
Constraints:
m == mat.lengthn == mat[i].length1 <= n, m <= 501 <= matrix[i][j] <= 10^5.- All elements in the matrix are distinct.
Solution
Approach: Row Minimums and Column Maximums
A lucky number has to be the minimum of its row and the maximum of its column. So compute, in one pass over the matrix:
rowMin[i]: the smallest value in rowi,colMax[j]: the largest value in columnj.
Then a cell (i, j) holds a lucky number exactly when rowMin[i] == colMax[j]. Because all values are distinct, equal values must be the same cell, so this value really is in row i and column j. (In Python, the same idea is the intersection of the set of row minimums and the set of column maximums.)
There is at most one lucky number. If a (row i, column j) and b (row k, column l) were both lucky, the value in row i, column l would be at least a (since a is its row's minimum) and at most b (since b is its column's maximum), so a < b. The value in row k, column j gives b < a the same way, which is impossible. The answer can also be empty, as in [[3,6],[7,1]].
Complexity: O(m * n) time and O(m + n) extra space.
class Solution:
def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
row_mins = {min(row) for row in matrix}
col_maxes = {max(col) for col in zip(*matrix)}
# The values are distinct, so a value in both sets is the min of its row and the max of its column.
return list(row_mins & col_maxes)