Count Submatrices That Sum Target - Google Top Interview Questions
Problem Statement :
You are given a two-dimensional integer matrix and an integer target. Return the number of submatrices in matrix whose sum equals target. Constraints 0 ≤ n, m ≤ 100 where n and m are the number of rows and columns in matrix Example 1 Input matrix = [ [0, -1], [0, 0] ] target = 0 Output 5 Explanation We have three 1 x 1 submatrices, one 2 x 1 submatrix and one 1 x 2 submatrix.
Solution :
Solution in C++ :
int solve(vector<vector<int>>& matrix, int target) {
int n = matrix.size();
int m = n == 0 ? 0 : matrix[0].size();
if (m > n) {
vector<vector<int>> transposeMatrix(m, vector<int>(n));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
transposeMatrix[j][i] = matrix[i][j];
}
}
return solve(transposeMatrix, target);
}
int res = 0;
for (int l = 0; l < m; l++) {
vector<int> a(n);
for (int r = l; r < m; r++) {
for (int i = 0; i < n; i++) {
a[i] += matrix[i][r];
}
unordered_map<int, int> prefCnt = {{0, 1}};
int pref = 0;
for (int i = 0; i < n; i++) {
pref += a[i];
auto it = prefCnt.find(pref - target);
if (it != end(prefCnt)) res += it->second;
prefCnt[pref]++;
}
}
}
return res;
}
Solution in Java :
import java.util.*;
class Solution {
public int solve(int[][] matrix, int target) {
int ret = 0;
RangeSumMatrix rsm = new RangeSumMatrix(matrix);
for (int i = 0; i < matrix.length; i++) {
for (int j = i; j < matrix.length; j++) {
for (int a = 0; a < matrix[0].length; a++) {
for (int b = a; b < matrix[0].length; b++) {
if (rsm.total(i, a, j, b) == target) {
ret++;
}
}
}
}
}
return ret;
}
}
class RangeSumMatrix {
private int[][] pf;
public RangeSumMatrix(int[][] matrix) {
pf = new int[matrix.length + 1][matrix[0].length + 1];
for (int i = 1; i <= matrix.length; ++i) {
for (int j = 1; j <= matrix[0].length; ++j) {
pf[i][j] = pf[i - 1][j] + pf[i][j - 1] - pf[i - 1][j - 1] + matrix[i - 1][j - 1];
}
}
}
public int total(int row0, int col0, int row1, int col1) {
return pf[row1 + 1][col1 + 1] - pf[row0][col1 + 1] - pf[row1 + 1][col0] + pf[row0][col0];
}
}
Solution in Python :
class Solution:
def solve(self, matrix, target):
matrix = [list(accumulate(row, initial=0)) for row in matrix]
N, M, res = len(matrix), len(matrix[0]), 0
for col1 in range(1, M):
for col2 in range(col1, M):
prev_sums = defaultdict(int, {0: 1})
run_sum = 0
for row in range(N):
run_sum += matrix[row][col2] - matrix[row][col1 - 1]
res += prev_sums[run_sum - target]
prev_sums[run_sum] += 1
return res
View More Similar Problems
Poisonous Plants
There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan
View Solution →AND xor OR
Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value
View Solution →Waiter
You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the
View Solution →Queue using Two Stacks
A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que
View Solution →Castle on the Grid
You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):
View Solution →Down to Zero II
You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.
View Solution →