LeetCode 2536: Increment Submatrices by One

ArrayMatrixPrefix Sum

Problem Description

Explanation

To solve this problem, we can iterate through each query and increment the corresponding submatrix in the matrix. We can achieve this by updating the values in the matrix based on the query parameters. After processing all queries, we return the modified matrix.

  • Initialize a 2D matrix mat filled with zeroes of size n x n.
  • Iterate through each query in the queries array.
    • For each query, update the submatrix in mat by incrementing the values by 1.
  • Return the modified matrix mat.

Time Complexity: O(n^2 + q), where n is the size of the matrix and q is the number of queries. Space Complexity: O(n^2) for the matrix mat.

Solutions

class Solution {
    public int[][] incrementMatrix(int n, int[][] queries) {
        int[][] mat = new int[n][n];
        
        for (int[] query : queries) {
            int row1 = query[0];
            int col1 = query[1];
            int row2 = query[2];
            int col2 = query[3];
            
            for (int i = row1; i <= row2; i++) {
                for (int j = col1; j <= col2; j++) {
                    mat[i][j]++;
                }
            }
        }
        
        return mat;
    }
}

Loading editor...