Lucky Numbers in a Matrix

easy array matrix

Problem

Given an m x n matrix of distinct integers, return all lucky numbers in any order. A lucky number is a value that is the smallest element in its row and at the same time the largest element in its column.

Inputmatrix = [[3,7,8],[9,11,13],[15,16,17]]
Output[15]
15 is the minimum of its row (15, 16, 17) and the maximum of its column (3, 9, 15), so it is lucky.

def lucky_numbers(matrix):
    row_min = {min(row) for row in matrix}
    col_max = {max(col) for col in zip(*matrix)}
    return list(row_min & col_max)
function luckyNumbers(matrix) {
  const rowMin = matrix.map(row => Math.min(...row));
  const colMax = matrix[0].map((_, j) =>
    Math.max(...matrix.map(row => row[j])));
  return rowMin.filter(v => colMax.includes(v));
}
class Solution {
    public List<Integer> luckyNumbers(int[][] matrix) {
        Set<Integer> rowMin = new HashSet<>();
        for (int[] row : matrix) {
            int lo = row[0];
            for (int v : row) lo = Math.min(lo, v);
            rowMin.add(lo);
        }
        List<Integer> res = new ArrayList<>();
        for (int j = 0; j < matrix[0].length; j++) {
            int hi = matrix[0][j];
            for (int[] row : matrix) hi = Math.max(hi, row[j]);
            if (rowMin.contains(hi)) res.add(hi);
        }
        return res;
    }
}
vector<int> luckyNumbers(vector<vector<int>>& matrix) {
    set<int> rowMin;
    for (auto& row : matrix)
        rowMin.insert(*min_element(row.begin(), row.end()));
    vector<int> res;
    for (int j = 0; j < (int)matrix[0].size(); j++) {
        int hi = matrix[0][j];
        for (auto& row : matrix) hi = max(hi, row[j]);
        if (rowMin.count(hi)) res.push_back(hi);
    }
    return res;
}
Time: O(m·n) Space: O(m + n)