Square Submatrix Sum Below Target - Google Top Interview Questions


Problem Statement :


You are given a two-dimensional list of non-negative integers matrix and a non-negative integer target. Return the area of the largest square sub-matrix whose sum is less than or equal to target. 

If there's no such matrix, return 0.

Constraints

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

Example 1

Input

matrix = [
    [3, 2, 1],

    [2, 0, 7],

    [1, 1, 9]

]

target = 10

Output

4

Explanation

This sub-matrix sums to 10:

[2, 1]

[0, 7]



Solution :



title-img




                        Solution in C++ :

int dp[255][255];
int solve(vector<vector<int>>& matrix, int target) {
    int r = matrix.size();
    int c = matrix[0].size();
    int ret = 0;
    for (int i = 1; i <= r; i++) {
        for (int j = 1; j <= c; j++) {
            dp[i][j] = matrix[i - 1][j - 1] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1];
            while (ret + 1 <= min(i, j) && dp[i][j] - dp[i - ret - 1][j] - dp[i][j - ret - 1] +
                                                   dp[i - ret - 1][j - ret - 1] <=
                                               target)
                ret++;
        }
    }
    return ret * ret;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    int[][] dp;
    int[][] matrix;
    public int area(int r1, int c1, int r2, int c2) {
        int m = matrix.length, n = matrix[0].length;
        if (r2 >= m || c2 >= n)
            return Integer.MAX_VALUE;
        return dp[r2 + 1][c2 + 1] + dp[r1][c1] - dp[r2 + 1][c1] - dp[r1][c2 + 1];
    }

    public boolean ok(int mid, int target) {
        int m = matrix.length, n = matrix[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (area(i, j, i + mid - 1, j + mid - 1) <= target)
                    return true;
            }
        }
        return false;
    }

    public int solve(int[][] mm, int target) {
        this.matrix = mm;
        int m = matrix.length;
        int n = matrix[0].length;
        dp = new int[m + 1][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];
            }
        }
        int res = 0;
        int left = 1;
        int right = Math.min(m, n);
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (ok(mid, target)) {
                res = mid * mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return res;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, matrix, target):
        n, m = len(matrix), len(matrix[0])

        def prefix_sum_with_padding():
            prefix = [[0 for i in range(m + 1)] for j in range(n + 1)]
            for i in range(1, n + 1):
                for j in range(1, m + 1):
                    prefix[i][j] = matrix[i - 1][j - 1]
                    prefix[i][j] += prefix[i][j - 1]
                    prefix[i][j] += prefix[i - 1][j]
                    prefix[i][j] -= prefix[i - 1][j - 1]
            return prefix

        prefix = prefix_sum_with_padding()

        def found_less_equal(side):
            for i in range(side, n + 1):
                for j in range(side, m + 1):
                    cur_sum = (
                        prefix[i][j]
                        - prefix[i - side][j]
                        - prefix[i][j - side]
                        + prefix[i - side][j - side]
                    )
                    if cur_sum <= target:
                        return True
            return False

        def binary_search_for_side():
            l, r = 0, max(n, m)
            while l <= r:
                mid = (l + r) // 2
                if found_less_equal(mid):
                    l = mid + 1
                else:
                    r = mid - 1
            return r

        side = binary_search_for_side()

        return side * side
                    


View More Similar Problems

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

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 →