LeetCode 1074: Number of Submatrices That Sum to Target Solution

Master LeetCode problem 1074 (Number of Submatrices That Sum to Target), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1074. Number of Submatrices That Sum to Target

Problem Explanation

Explanation

To solve this problem, we can use the concept of prefix sum along with hashing. We iterate over all possible pairs of rows and for each pair, we calculate the prefix sum of columns between these two rows. Then, we use a hashmap to store the frequency of prefix sums encountered so far. As we iterate through the columns, we calculate the sum of submatrices in this range by subtracting the prefix sum from the target. If the target - sum is present in the hashmap, we increment the count of submatrices by the corresponding frequency. Finally, we update the hashmap with the current prefix sum frequency.

Time Complexity: O(m^2 * n) where m is the number of rows and n is the number of columns in the matrix. Space Complexity: O(n).

Solution Code

class Solution {
    public int numSubmatrixSumTarget(int[][] matrix, int target) {
        int m = matrix.length;
        int n = matrix[0].length;
        int count = 0;

        for (int i = 0; i < m; i++) {
            int[] sum = new int[n];
            for (int j = i; j < m; j++) {
                Map<Integer, Integer> map = new HashMap<>();
                int prefixSum = 0;
                map.put(0, 1);
                
                for (int k = 0; k < n; k++) {
                    sum[k] += matrix[j][k];
                    prefixSum += sum[k];
                    count += map.getOrDefault(prefixSum - target, 0);
                    map.put(prefixSum, map.getOrDefault(prefixSum, 0) + 1);
                }
            }
        }

        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1074 (Number of Submatrices That Sum to Target)?

This page provides optimized solutions for LeetCode problem 1074 (Number of Submatrices That Sum to Target) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1074 (Number of Submatrices That Sum to Target)?

The time complexity for LeetCode 1074 (Number of Submatrices That Sum to Target) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1074 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1074 in Java, C++, or Python.

Back to LeetCode Solutions