Modify the Matrix - Problem

Given a 0-indexed m x n integer matrix matrix, create a new 0-indexed matrix called answer. Make answer equal to matrix, then replace each element with the value -1 with the maximum element in its respective column.

Return the matrix answer.

Input & Output

Example 1 — Basic Matrix
$ Input: matrix = [[1,2,-1],[4,-1,6],[7,8,9]]
Output: [[1,2,9],[4,8,6],[7,8,9]]
💡 Note: Column maximums are [7,8,9]. Replace -1 in position [0,2] with 9, and -1 in position [1,1] with 8.
Example 2 — Multiple -1s in Same Column
$ Input: matrix = [[3,-1],[5,2]]
Output: [[3,2],[5,2]]
💡 Note: Column maximums are [5,2]. Replace -1 in position [0,1] with maximum of column 1, which is 2.
Example 3 — No -1s
$ Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,2,3],[4,5,6]]
💡 Note: No -1 elements to replace, matrix remains unchanged.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m * n ≤ 105
  • -109 ≤ matrix[i][j] ≤ 109
  • The input contains at least one non-negative number.

Visualization

Tap to expand
Modify Matrix: Replace -1 with Column Maximum12-14-16789Original MatrixMax: 7Max: 8Max: 9129486789Modified Matrix✓ All -1s replaced with their respective column maximums
Understanding the Visualization
1
Input Matrix
Matrix with some -1 elements that need replacement
2
Find Column Max
Compute maximum value for each column
3
Replace -1s
Replace each -1 with its column maximum
Key Takeaway
🎯 Key Insight: Pre-compute column maximums to avoid redundant scans when replacing multiple -1s
Asked in
Amazon 15 Google 12 Microsoft 8
8.5K Views
Medium Frequency
~10 min Avg. Time
245 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