
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							Submatrices That Sum to Target
								Certification: Advanced Level
								Accuracy: 100%
								Submissions: 1
								Points: 15
							
							Write a Java program to count the number of submatrices in a given matrix that sum to a target value. A submatrix is a contiguous rectangular region within the matrix.
Example 1
- Input: matrix = [ [0, 1, 0], [1, 1, 1], [0, 1, 0] ] target = 3
 - Output: 4
 - Explanation: Step 1: The matrix has dimensions 3x3 and the target is 3. Step 2: There are 4 submatrices that sum to 3: - The 1x3 submatrix at row 1, columns 0-2: [1, 1, 1] - The 3x1 submatrix at column 1, rows 0-2: [1, 1, 1] - The 2x2 submatrix at rows 0-1, columns 0-1: [[0, 1], [1, 1]] - The 2x2 submatrix at rows 0-1, columns 1-2: [[1, 0], [1, 1]] Step 3: The total count is 4.
 
Example 2
- Input: matrix = [ [1, -1], [-1, 1] ] target = 0
 - Output: 5
 - Explanation: Step 1: The matrix has dimensions 2x2 and the target is 0. Step 2: There are 5 submatrices that sum to 0: - The 1x2 submatrix at row 0, columns 0-1: [1, -1] - The 1x2 submatrix at row 1, columns 0-1: [-1, 1] - The 2x1 submatrix at column 0, rows 0-1: [1, -1] - The 2x1 submatrix at column 1, rows 0-1: [-1, 1] - The 2x2 submatrix at rows 0-1, columns 0-1: [[1, -1], [-1, 1]] Step 3: The total count is 5.
 
Constraints
- 1 <= matrix.length <= 100
 - 1 <= matrix[0].length <= 100
 - -1000 <= matrix[i][j] <= 1000
 - -10^8 <= target <= 10^8
 - Time Complexity: O(r^2 * c), where r is the number of rows and c is the number of columns
 - Space Complexity: O(c), where c is the number of columns
 
Editorial
									
												
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. | ||||
Solution Hints
- Use prefix sums to efficiently calculate the sum of any submatrix
 - For each pair of rows (top and bottom), calculate the sum of each column between these rows
 - Convert the 2D problem to a 1D problem by computing the sum array for each fixed pair of rows
 - Use a hash map to count the number of subarrays that sum to the target
 - Iterate through the cumulative sums and check if (currentSum - target) exists in the hash map
 - Update the count based on the frequency found in the hash map
 - Return the final count of valid submatrices