Matrix Rectangular Sums - Facebook Top Interview Questions


Problem Statement :


Given a two-dimensional list of integers matrix and an integer k, return a new matrix M of the same dimensions where M[i][j] is the sum of all numbers

sum(matrix[r][c]) for all (i - k ≤ r ≤ i + k, j - k ≤ c ≤ j + k)

Constraints

n, m ≤ 250 where n and m is the number of rows and columns in matrix

Example 1

Input

matrix = [

    [1, 2, 3],

    [4, 5, 6],

    [7, 8, 9]

]

k = 1

Output

[

    [12, 21, 16],

    [27, 45, 33],

    [24, 39, 28]


]



Solution :



title-img




                        Solution in C++ :

int rectangle(vector<vector<int>>& dp, int r1, int c1, int r2, int c2) {
    int res = dp[r2 + 1][c2 + 1];
    res -= dp[r2 + 1][c1];
    res -= dp[r1][c2 + 1];
    res += dp[r1][c1];
    return res;
}

vector<vector<int>> solve(vector<vector<int>>& matrix, int k) {
    int m = matrix.size(), n = matrix[0].size();
    vector<vector<int>> res(m, vector<int>(n));
    vector<vector<int>> dp(m + 1, vector<int>(n + 1));

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

    for (int r = 0; r < m; r++) {
        for (int c = 0; c < n; c++) {
            int r1 = max(0, r - k);
            int c1 = max(0, c - k);
            int r2 = min(m - 1, r + k);
            int c2 = min(n - 1, c + k);

            res[r][c] = rectangle(dp, r1, c1, r2, c2);
        }
    }
    return res;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int[][] solve(int[][] matrix, int k) {
        RangeSumMatrix rsm = new RangeSumMatrix(matrix);
        int[][] ret = new int[matrix.length][matrix[0].length];
        for (int i = 0; i < ret.length; i++) {
            for (int j = 0; j < ret[0].length; j++) {
                ret[i][j] = rsm.total(i - k, j - k, i + k, j + k);
            }
        }
        return ret;
    }
}
class RangeSumMatrix {
    int[][] matrix;
    public RangeSumMatrix(int[][] matrix) {
        this.matrix = matrix;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 1; j < matrix[0].length; j++) {
                matrix[i][j] += matrix[i][j - 1];
            }
        }
    }

    public int total(int row0, int col0, int row1, int col1) {
        row0 = Math.max(0, row0);
        row1 = Math.min(matrix.length - 1, row1);
        col0 = Math.max(0, col0);
        col1 = Math.min(matrix[0].length - 1, col1);

        int ret = 0;
        for (int i = row0; i <= row1; i++) {
            ret += matrix[i][col1];
            if (col0 != 0) {
                ret -= matrix[i][col0 - 1];
            }
        }
        return ret;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, A, k):
        R, C = len(A), len(A[0])
        for r in range(R):
            for c in range(C):
                if r:
                    A[r][c] += A[r - 1][c]
                if c:
                    A[r][c] += A[r][c - 1]
                if r and c:
                    A[r][c] -= A[r - 1][c - 1]

        def get_sum(top, left, bottom, right):
            top = max(top, 0)
            left = max(left, 0)
            bottom = min(bottom, R - 1)
            right = min(right, C - 1)

            return (
                A[bottom][right]
                - (A[top - 1][right] if top else 0)
                - (A[bottom][left - 1] if left else 0)
                + (A[top - 1][left - 1] if top and left else 0)
            )

        return [[get_sum(r - k, c - k, r + k, c + k) for c in range(C)] for r in range(R)]
                    


View More Similar Problems

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →