githubEdit

27. Number of Submatrix have Sum X

βœ… GFG solution to Number of Submatrix have Sum X: count square submatrices with specific sum using 2D prefix sum technique. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

Given a matrix mat[][] of size n Γ— m and an integer x, find the number of square submatrices whose sum of elements is equal to x.

πŸ“˜ Examples

Example 1

Input: mat[][] = [[2, 4, 7, 8, 10], 
                  [3, 1, 1, 1, 1], 
                  [9, 11, 1, 2, 1], 
                  [12, -17, 1, 1, 1]], x = 10
Output: 3
Explanation: There are 3 square sub-matrices whose sum of elements equals 10.

image

Example 2

Input: mat[][] = [[3, 3, 5, 3], 
                  [2, 2, 2, 6], 
                  [11, 2, 2, 4]], x = 1
Output: 0
Explanation: There is no square sub-matrix whose sum of elements is 1.

Example 3

πŸ”’ Constraints

  • $1 \le n, m \le 100$

  • $-10^3 \le \text{mat}[i] \le 10^3$

  • $-10^9 \le x \le 10^9$

βœ… My Approach

The optimal solution uses 2D Prefix Sum with Square Enumeration:

2D Prefix Sum Technique

  1. Build 2D Prefix Sum:

    • Create a prefix sum matrix where pre[i][j] stores sum of all elements from (0,0) to (i-1,j-1).

    • Formula: pre[i][j] = mat[i-1][j-1] + pre[i-1][j] + pre[i][j-1] - pre[i-1][j-1]

  2. Enumerate All Square Sizes:

    • Try all possible square sizes from 1Γ—1 to min(n,m) Γ— min(n,m).

    • For each size, check all possible top-left positions.

  3. Calculate Square Sum:

    • For a square of size sz ending at position (i,j):

    • Sum = pre[i][j] - pre[i-sz][j] - pre[i][j-sz] + pre[i-sz][j-sz]

    • This uses inclusion-exclusion principle on prefix sums.

  4. Count Valid Squares:

    • If calculated sum equals x, increment counter.

    • Return total count after checking all possible squares.

Key Advantage: 2D prefix sum allows O(1) submatrix sum calculation after O(nΓ—m) preprocessing.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n Γ— m Γ— min(n,m)Β²), where we build prefix sum in O(nΓ—m), then check all squares. For each of O(min(n,m)) sizes, we check O(nΓ—m) positions with O(1) sum calculation per position.

  • Expected Auxiliary Space Complexity: O(n Γ— m), as we use a 2D prefix sum array of the same size as the input matrix to store cumulative sums.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Row Prefix Sum with Sliding Window

πŸ’‘ Algorithm Steps:

  1. Compute row-wise prefix sums for efficient row sum calculation.

  2. For each square size, use sliding window vertically.

  3. Maintain cumulative sum of rows as we slide.

  4. Count squares with sum equal to x.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n Γ— m Γ— min(n,m)) - Optimized sliding window

  • Auxiliary Space: πŸ’Ύ O(n Γ— m) - Row prefix sum array

βœ… Why This Approach?

  • Efficient sliding window reduces redundant calculations

  • Row prefix sum enables O(1) row range queries

  • Good balance between complexity and performance

πŸ“Š 3️⃣ Brute Force Approach

πŸ’‘ Algorithm Steps:

  1. For each possible top-left corner of square submatrix.

  2. For each possible square size from that corner.

  3. Calculate sum by iterating through all elements.

  4. Count squares with sum equal to x.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(nΒ² Γ— mΒ² Γ— min(n,m)) - Nested loops with sum calculation

  • Auxiliary Space: πŸ’Ύ O(1) - Constant extra space

βœ… Why This Approach?

  • Simple and straightforward implementation

  • No preprocessing required

  • Good for understanding the problem

Note: This approach results in Time Limit Exceeded (TLE) for large inputs (fails ~1110/1113 test cases due to time constraints).

πŸ“Š 4️⃣ Optimized Brute Force with Incremental Sum

πŸ’‘ Algorithm Steps:

  1. For each top-left corner and square size.

  2. Build square sum incrementally by adding new row and column.

  3. Reuse previous smaller square's sum.

  4. Count valid squares efficiently.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n Γ— m Γ— min(n,m)Β²) - Incremental sum building

  • Auxiliary Space: πŸ’Ύ O(1) - Constant space

βœ… Why This Approach?

  • Better than pure brute force

  • Incremental sum reduces redundant work

  • Still easy to understand and implement

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🎯 2D Prefix Sum

🟒 O(nΓ—mΓ—minΒ²)

🟑 O(nΓ—m)

πŸš€ O(1) submatrix query

πŸ’Ύ Extra space for prefix array

πŸ“Š Row Prefix + Sliding

🟒 O(nΓ—mΓ—min)

🟑 O(nΓ—m)

⚑ Most time efficient

πŸ”§ Complex sliding logic

πŸ”„ Brute Force

πŸ”΄ O(nΒ²Γ—mΒ²Γ—min)

🟒 O(1)

πŸ“– Simple to understand

🐌 Very slow for large inputs

πŸ“ˆ Incremental Sum

🟑 O(nΓ—mΓ—minΒ²)

🟒 O(1)

πŸ’Ύ Space efficient

πŸ”§ Still multiple nested loops

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Optimal time complexity

πŸ₯‡ Row Prefix + Sliding

β˜…β˜…β˜…β˜…β˜…

πŸ“– Balanced performance

πŸ₯ˆ 2D Prefix Sum

β˜…β˜…β˜…β˜…β˜…

πŸ’Ύ Memory constrained

πŸ₯‰ Incremental Sum

β˜…β˜…β˜…β˜†β˜†

🎯 Learning purposes

πŸ… Brute Force

β˜…β˜…β˜…β˜†β˜†

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated