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
Matrix Modification ProcessOriginal Matrix1-13456281Column Max: [4, 8, 6]Replace -1with col maxResult Matrix183456281Algorithm Steps:1. First Pass: Scan matrix to find maximum in each column (ignore -1 values)2. Store Maximums: Keep column max values in array: [4, 8, 6]3. Second Pass: Replace each -1 with its column's maximum valueโฐ Time: O(mร—n) | ๐Ÿ’พ Space: O(n) | โœ… Optimal Solution
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.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
23.8K Views
Medium Frequency
~8 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen