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 the Matrix Two-Pass Optimization Approach INPUT matrix (3x3) 1 2 -1 4 -1 6 7 8 9 Col 0 Col 1 Col 2 = cells with -1 Input Values matrix = [ [1, 2, -1], [4, -1, 6], [7, 8, 9] ] ALGORITHM STEPS 1 Copy Matrix answer = matrix.copy() 2 Find Column Max Pass 1: Scan each column Col 0 Col 1 Col 2 7 8 9 colMax = [7, 8, 9] 3 Replace -1 Values Pass 2: If val == -1, replace with colMax 4 Return Result Return modified answer Complexity Time: O(m * n) Space: O(n) for colMax FINAL RESULT answer (3x3) 1 2 9 4 8 6 7 8 9 = replaced values Transformations: -1 at [0,2] --> 9 -1 at [1,1] --> 8 Output [[1,2,9],[4,8,6],[7,8,9]] OK - All -1 replaced! Key Insight: Two-pass optimization: First pass finds max value in each column (ignoring -1), second pass replaces all -1 values with corresponding column max. This ensures O(m*n) time with only O(n) extra space for storing column maximums. TutorialsPoint - Modify the Matrix | Two-Pass Optimization
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