#1380
Lucky Numbers in a Matrix
EasyArrayMatrixArrayMatrix
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking each element repeatedly, we can first find the minimum of each row and the maximum of each column, then check for lucky numbers in a single pass.
⚙️
Algorithm
3 steps- 1Step 1: Create a list to store the minimum of each row.
- 2Step 2: Create a list to store the maximum of each column.
- 3Step 3: Iterate through the matrix and check if each minimum is also the maximum in its column.
solution.py4 lines
1def luckyNumbers(matrix):
2 min_row = [min(row) for row in matrix]
3 max_col = [max(matrix[i][j] for i in range(len(matrix))) for j in range(len(matrix[0]))]
4 return [min_row[i] for i in range(len(min_row)) if min_row[i] == max_col[matrix[i].index(min_row[i])]]ℹ
Complexity note: We perform linear scans to find minimums and maximums, leading to O(n) time complexity overall.
- 1Lucky numbers must satisfy two conditions: min in row and max in column.
- 2Using pre-computed lists for row mins and column maxes reduces redundant checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.