#1074

Number of Submatrices That Sum to Target

Hard 2D → 1D prefix + HashMap

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count all non-empty rectangles in a matrix whose elements sum to a target.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: count rectangles in a grid with a given sum.

Why this works: fix a top row and a bottom row; squash the columns between them into one array of column sums. Now it's "subarray sum equals k" on that array.

Example: rows 0..1 of [[0,1],[1,0]] squashed → column sums [1, 1]

subarrays summing to 1: [1], [1] → 2repeat for every pair of rows and add up

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Enumerating all four corners directly — O(m² n²) and too slow.