Tutorialspoint
Problem
Solution
Submissions

Count of Submatrices

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the number of non-empty submatrices that sum to a given target value. A submatrix is a rectangular region within the matrix. You need to count all possible submatrices (including single elements) whose sum equals the target.

Example 1
  • Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
  • Output: 4
  • Explanation:
    • There are 4 submatrices that sum to 0.
    • Single elements: matrix[0][0] = 0, matrix[0][2] = 0, matrix[2][0] = 0, matrix[2][2] = 0.
    • These 4 submatrices each have sum = 0.
    • Therefore, answer is 4.
Example 2
  • Input: matrix = [[1,-1],[-1,1]], target = 0
  • Output: 5
  • Explanation:
    • Submatrices with sum 0 are: [1,-1] (first row), [-1,1] (second row), [1;-1] (first column), [-1;1](secondcolumn).
    • And the entire 2x2 matrix [[1,-1],[-1,1]].
    • Total count = 5 submatrices.
Constraints
  • 1 ≤ matrix.length ≤ 100
  • 1 ≤ matrix[0].length ≤ 100
  • -1000 ≤ matrix[i][j] ≤ 1000
  • -10^8 ≤ target ≤ 10^8
  • Time Complexity: O(m^2 * n^2)
  • Space Complexity: O(n)
ArraysMatrixEYZomato
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use prefix sum technique to calculate submatrix sums efficiently
  • Fix top and bottom rows, then use 1D subarray sum technique
  • For each column range, maintain running sum and use hash map
  • Count subarrays with target sum using the difference technique
  • Iterate through all possible top-bottom row combinations

Steps to solve by this approach:

 Step 1: Iterate through all possible top and bottom row combinations

 Step 2: For each top-bottom pair, calculate column-wise sums to reduce to 1D problem
 Step 3: Use hash map to store prefix sums and their frequencies
 Step 4: For each column, calculate running prefix sum
 Step 5: Check if (prefixSum - target) exists in hash map
 Step 6: Add the count of such occurrences to result
 Step 7: Update hash map with current prefix sum

Submitted Code :