VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-sub-matrices-sum-divisible-k/

⇱ Count sub-matrices having sum divisible 'k' - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count sub-matrices having sum divisible 'k'

Last Updated : 8 Mar, 2024

Given a n x n matrix of integers and a positive integer k. The problem is to count all sub-matrices having sum divisible by the given value k.

Examples: 

Input : mat[][] = { {5, -1, 6},
 {-2, 3, 8},
 {7, 4, -9} }

 k = 4

Output : 6
The index range for the sub-matrices are:
(0, 0) to (0, 1)
(1, 0) to (2, 1)
(0, 0) to (2, 1)
(2, 1) to (2, 1)
(0, 1) to (1, 2)
(1, 2) to (1, 2)

Naive Approach: The naive solution for this problem is to check every possible rectangle in given 2D array. This solution requires 4 nested loops and time complexity of this solution would be O(n^4).

Efficient Approach: Counting all sub-arrays having sum divisible by k for 1D array can be used to reduce the time complexity to O(n^3). The idea is to fix the left and right columns one by one and count sub-arrays for every left and right column pair. Calculate sum of elements in every row from left to right and store these sums in an array say temp[]. So temp[i] indicates sum of elements from left to right in row i. Count sub-arrays in temp[] having sum divisible by k. This count is the number of sub-matrices having sum divisible by k with left and right as boundary columns. Sum up all the counts for each temp[] with different left and right column pairs.

Implementation:


Output
Count = 6

Time Complexity: O(n^3). 
Auxiliary Space: O(n).

Comment
Article Tags: