LeetCode 3033: Modify the Matrix Solution

Master LeetCode problem 3033 (Modify the Matrix), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3033. Modify the Matrix

Problem Explanation

Explanation:

To solve this problem, we need to iterate over each element in the matrix and check if the value is -1. If it is -1, we need to replace it with the maximum element in its column. We can achieve this by first finding the maximum value in each column and then updating the matrix accordingly.

Algorithm:

  1. Initialize an array maxInCol of size n to store the maximum value in each column.
  2. Iterate over each element in the matrix and update maxInCol accordingly.
  3. Iterate over each element in the matrix again and if the value is -1, replace it with the corresponding value from maxInCol.
  4. Return the modified matrix.

Time Complexity: O(m * n) where m is the number of rows and n is the number of columns in the matrix.

Space Complexity: O(n) for the maxInCol array.

Solution Code

class Solution {
    public int[][] modifyMatrix(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;

        int[] maxInCol = new int[n];
        for (int j = 0; j < n; j++) {
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < m; i++) {
                max = Math.max(max, matrix[i][j]);
            }
            maxInCol[j] = max;
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == -1) {
                    matrix[i][j] = maxInCol[j];
                }
            }
        }

        return matrix;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3033 (Modify the Matrix)?

This page provides optimized solutions for LeetCode problem 3033 (Modify the Matrix) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3033 (Modify the Matrix)?

The time complexity for LeetCode 3033 (Modify the Matrix) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3033 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3033 in Java, C++, or Python.

Back to LeetCode Solutions