Skip to content

Commit dca3528

Browse files
committedApr 2, 2025
Add solution #1074
1 parent f7ff7d4 commit dca3528

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed
 

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,114 LeetCode solutions in JavaScript
1+
# 1,115 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -854,6 +854,7 @@
854854
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
855855
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
856856
1073|[Adding Two Negabinary Numbers](./solutions/1073-adding-two-negabinary-numbers.js)|Medium|
857+
1074|[Number of Submatrices That Sum to Target](./solutions/1074-number-of-submatrices-that-sum-to-target.js)|Hard|
857858
1079|[Letter Tile Possibilities](./solutions/1079-letter-tile-possibilities.js)|Medium|
858859
1081|[Smallest Subsequence of Distinct Characters](./solutions/1081-smallest-subsequence-of-distinct-characters.js)|Medium|
859860
1092|[Shortest Common Supersequence](./solutions/1092-shortest-common-supersequence.js)|Hard|
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 1074. Number of Submatrices That Sum to Target
3+
* https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/
4+
* Difficulty: Hard
5+
*
6+
* Given a matrix and a target, return the number of non-empty submatrices that sum to target.
7+
*
8+
* A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and
9+
* y1 <= y <= y2.
10+
*
11+
* Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some
12+
* coordinate that is different: for example, if x1 != x1'.
13+
*/
14+
15+
/**
16+
* @param {number[][]} matrix
17+
* @param {number} target
18+
* @return {number}
19+
*/
20+
var numSubmatrixSumTarget = function(matrix, target) {
21+
const rows = matrix.length;
22+
const cols = matrix[0].length;
23+
let result = 0;
24+
25+
for (let i = 0; i < rows; i++) {
26+
const prefixSums = new Array(cols).fill(0);
27+
for (let j = i; j < rows; j++) {
28+
const sumFreq = new Map([[0, 1]]);
29+
let currentSum = 0;
30+
31+
for (let k = 0; k < cols; k++) {
32+
prefixSums[k] += matrix[j][k];
33+
currentSum += prefixSums[k];
34+
result += sumFreq.get(currentSum - target) || 0;
35+
sumFreq.set(currentSum, (sumFreq.get(currentSum) || 0) + 1);
36+
}
37+
}
38+
}
39+
40+
return result;
41+
};

0 commit comments

Comments
 (0)
Please sign in to comment.