1380. Lucky Numbers in a Matrix
Given a 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 such that it is the minimum element in its row and maximum in its column.
To determine the lucky numbers in a matrix, we can follow these steps:
Here’s a step-by-step breakdown of the approach:
m
is the number of rows and n
is the number of columns.Here is the Python code that implements the above strategy:
def luckyNumbers(matrix):
min_in_rows = []
m, n = len(matrix), len(matrix[0])
# Step 1: Find the minimum in each row
for i in range(m):
min_val = min(matrix[i])
min_index = matrix[i].index(min_val)
min_in_rows.append((min_val, min_index))
# Step 2: Verify if the minimums are maximum in their respective columns
lucky_nums = []
for (min_val, col_index) in min_in_rows:
is_lucky = True
for row in range(m):
if matrix[row][col_index] > min_val:
is_lucky = False
break
if is_lucky:
lucky_nums.append(min_val)
return lucky_nums
matrix = [
[3, 7, 8],
[9, 11, 13],
[15, 16, 17]
]
print(luckyNumbers(matrix)) # Output: [15]
In this example:
The provided code correctly identifies the lucky numbers in the given matrix by ensuring that each candidate is both a row minimum and column maximum. The approach efficiently checks each condition using nested loops, maintaining a manageable O(m * n) time complexity.
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?