Skip to content

1380. Lucky Numbers in a Matrix 👍

  • Time: $O(mn)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  vector<int> luckyNumbers(vector<vector<int>>& matrix) {
    for (const vector<int>& row : matrix) {
      const int minIndex = distance(row.begin(), ranges::min_element(row));
      if (row[minIndex] == maxNumOfColumn(matrix, minIndex))
        return {row[minIndex]};
    }
    return {};
  }

 private:
  int maxNumOfColumn(const vector<vector<int>>& matrix, int j) {
    int res = 0;
    for (int i = 0; i < matrix.size(); ++i)
      res = max(res, matrix[i][j]);
    return res;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
  public List<Integer> luckyNumbers(int[][] matrix) {
    for (int[] row : matrix) {
      final int minIndex = getMinIndex(row);
      if (row[minIndex] == maxNumOfColumn(matrix, minIndex))
        return List.of(row[minIndex]);
    }
    return new ArrayList<>();
  }

  private int getMinIndex(int[] row) {
    int minIndex = 0;
    for (int j = 0; j < row.length; ++j)
      if (row[j] < row[minIndex])
        minIndex = j;
    return minIndex;
  }

  private int maxNumOfColumn(int[][] matrix, int j) {
    int res = 0;
    for (int i = 0; i < matrix.length; ++i)
      res = Math.max(res, matrix[i][j]);
    return res;
  }
}
1
2
3
4
5
6
7
class Solution:
  def luckyNumbers(self, matrix: list[list[int]]) -> list[int]:
    for row in matrix:
      minIndex = row.index(min(row))
      if row[minIndex] == max(list(zip(*matrix))[minIndex]):
        return [row[minIndex]]
    return []