LeetCode 1380: Lucky Numbers in a Matrix Solution
Master LeetCode problem 1380 (Lucky Numbers in a Matrix), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
- We will iterate through each cell in the matrix and check if it is a lucky number.
- For each cell, we will find the minimum element in its row and the maximum element in its column.
- If the current cell value is both the minimum in its row and the maximum in its column, it is a lucky number.
- We will store all lucky numbers found in a list and return the list as the result.
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns in the matrix. Space Complexity: O(1) excluding the output list.
Solution Code
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<Integer> luckyNumbers (int[][] matrix) {
List<Integer> luckyNums = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
int minRow = Integer.MAX_VALUE;
int colIdx = -1;
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] < minRow) {
minRow = matrix[i][j];
colIdx = j;
}
}
int maxCol = matrix[i][colIdx];
for (int k = 0; k < matrix.length; k++) {
if (matrix[k][colIdx] > maxCol) {
maxCol = -1;
break;
}
}
if (minRow == maxCol) {
luckyNums.add(minRow);
}
}
return luckyNums;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1380 (Lucky Numbers in a Matrix)?
This page provides optimized solutions for LeetCode problem 1380 (Lucky Numbers in a Matrix) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1380 (Lucky Numbers in a Matrix)?
The time complexity for LeetCode 1380 (Lucky Numbers in a Matrix) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1380 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1380 in Java, C++, or Python.