Skip to main content
LeetCode 1074, Hard. Topics: Array, Hash Table, Matrix, Prefix Sum. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 12 parametrized pytest cases, and a playground notebook:

Problem

Given a <code>matrix</code> and a <code>target</code>, return the number of non-empty submatrices that sum to <code>target</code>. A submatrix <code>x1, y1, x2, y2</code> is the set of all cells <code>matrix[x][y]</code> with <code>x1 <= x <= x2</code> and <code>y1 <= y <= y2</code>. Two submatrices <code>(x1, y1, x2, y2)</code> and <code>(x1’, y1’, x2’, y2’)</code> are different if they have some coordinate that is different: for example, if <code>x1 != x1’</code>.

Examples

Example 1

Constraints

  • <code>1 <= matrix.length <= 100</code>
  • <code>1 <= matrix[0].length <= 100</code>
  • <code>-1000 <= matrix[i][j] <= 1000</code>
  • <code>-10<sup>8</sup> <= target <= 10<sup>8</sup></code>

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026