HardArrayHash TableMatrixPrefix Sum

Number of Submatrices That Sum to Target

LeetCode
1 approach, code in all languages

You are given an m x n integer matrix and an integer target. Return the number of non-empty submatrices whose elements add up to exactly target.

A submatrix is defined by a contiguous range of rows (x1 to x2) and a contiguous range of columns (y1 to y2), and it includes every cell whose row is in [x1, x2] and column is in [y1, y2]. Two submatrices are counted as different if they differ in any of these four boundary indices, even if their contents are identical.

Example 1

Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0

Output: 4

There are four submatrices that sum to 0, each consisting of a single 0 cell at the four corners of the matrix.

Example 2

Input: matrix = [[1,-1],[-1,1]], target = 0

Output: 5

Five distinct submatrices sum to 0, including the full matrix and the four 1x2 or 2x1 bands that pair a 1 with a -1.

Constraints

  • 1 <= matrix.length <= 100
  • 1 <= matrix[0].length <= 100
  • -1000 <= matrix[i][j] <= 1000
  • -10^8 <= target <= 10^8
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now