Modify the Matrix - Problem
You're given an m ร n integer matrix where some elements are marked with -1 as placeholders. Your task is to transform this matrix by replacing each -1 with the maximum value in its respective column.
Think of it like filling in missing data in a spreadsheet - wherever you see a -1, look up the column to find the highest number and use that as the replacement value.
Goal: Create a new matrix where all -1 values are replaced with their column's maximum value.
Example: If column 0 has values [3, -1, 5], the -1 should become 5 (the maximum in that column).
Input & Output
example_1.py โ Basic Matrix
$
Input:
matrix = [[1,-1],[4,5]]
โบ
Output:
[[1,5],[4,5]]
๐ก Note:
Column 0 has values [1,4], max is 4. Column 1 has values [-1,5], max is 5 (ignoring -1). So matrix[0][1] = -1 becomes 5.
example_2.py โ Multiple -1s
$
Input:
matrix = [[3,-1],[5,2]]
โบ
Output:
[[3,2],[5,2]]
๐ก Note:
Column 0: max of [3,5] is 5. Column 1: max of [-1,2] is 2. The -1 at position (0,1) becomes 2.
example_3.py โ All -1s in column
$
Input:
matrix = [[1,2,3],[-1,-1,-1],[4,5,6]]
โบ
Output:
[[1,2,3],[4,5,6],[4,5,6]]
๐ก Note:
Column maximums are [4,5,6]. All -1s in row 1 are replaced with their respective column maximums.
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 โค m, n โค 50
- -1 โค matrix[i][j] โค 100
- The input is guaranteed to have at least one non-(-1) value in each column that contains a -1
Visualization
Tap to expand
Understanding the Visualization
1
Identify Missing Values
Find all -1 values that need to be replaced
2
Calculate Column Maximums
For each column, find the maximum non-(-1) value
3
Replace Values
Replace each -1 with its column's maximum value
4
Return Result
All missing values filled with appropriate maximums
Key Takeaway
๐ฏ Key Insight: Pre-computing column maximums eliminates redundant scanning and achieves optimal O(mรn) time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code