Leetcode 1380. Lucky Numbers in a Matrix
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 that is the minimum element in its row and the maximum in its column.
For simplicity, let’s assume the matrix is always non-empty and contains only distinct integers.
To find the lucky numbers, we’ll follow these steps:
Let’s implement the strategy in Java:
import java.util.ArrayList;
import java.util.List;
public class LuckyNumbersInMatrix {
public List<Integer> luckyNumbers (int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
List<Integer> luckyNumbers = new ArrayList<>();
// Step 1: Identify the minimum elements in each row
int[] minRow = new int[m];
int[] minRowColIndex = new int[m];
for (int i = 0; i < m; i++) {
int min = Integer.MAX_VALUE;
for (int j = 0; j < n; j++) {
if (matrix[i][j] < min) {
min = matrix[i][j];
minRowColIndex[i] = j;
}
}
minRow[i] = min;
}
// Step 2: Check if these minimum elements are the maximum in their respective columns
for (int i = 0; i < m; i++) {
int col = minRowColIndex[i];
int minValue = minRow[i];
boolean isMaxInCol = true;
for (int k = 0; k < m; k++) {
if (matrix[k][col] > minValue) {
isMaxInCol = false;
break;
}
}
if (isMaxInCol) {
luckyNumbers.add(minValue);
}
}
return luckyNumbers;
}
}
Thus, the overall time complexity is (O(m \times (n + m))), which simplifies to (O(m \times n + m^2)). For large (m) and (n), this will be dominated by the (m \times n) term.
The space complexity is (O(m)), needed for storing the minimum elements and their column indexes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?