Given a matrix (or 2D array) a of integers, find prefix sum matrix for it. Let prefix sum matrix be psa. The value of psa[i][j] contains sum of all values which are above it or on left of it.
Prerequisite: Prefix Sum – 1D
A simple solution is to find psa[i][j] by traversing and adding values from a to a[i][j]. Time complexity o this solution is O(R * C * R * C).
An efficient solution is to use previously computed values to compute psa[i][j]. Unlike 1D array prefix sum, this is tricky, here if we simply add psa[i][j-1] and psa[i-1][j], we get sum of elements from a to a[i-1][j-1] twice, so we subtract psa[i-1][j-1].
psa = psa + psa - psa + a = 6 + 6 - 4 + 1 = 9 The general formula: psa[i][j] = psa[i-1][j] + psa[i][j-1] - psa[i-1][j-1] + a[i][j] Corner Cases (First row and first column) If i = 0 and j = 0 psa[i][j] = a[i][j] If i = 0 and j > 0 psa[i][j] = psa[i][j-1] + a[i][j] If i > 0 and j = 0 psa[i][j] = psa[i-1][j] + a[i][j]
Below is the implementation of the above approach
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20
Time Complexity : O(R*C)
Auxiliary Space : O(R*C)
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Rearrange the array to maximize the number of primes in prefix sum of the array
- Count the number of primes in the prefix sum array of the given array
- Maximize the sum of array by multiplying prefix of array with -1
- Maximum sum increasing subsequence from a prefix and a given element after prefix is must
- Prefix Product Array
- Longest prefix that contains same number of X and Y in an array
- Prefix sum array in Python using accumulate function
- Maximize the sum of array after multiplying a prefix and suffix by -1
- Maximum array sum with prefix and suffix multiplications with -1 allowed
- Prefix Sum Array - Implementation and Applications in Competitive Programming
- Index with Minimum sum of prefix and suffix sums in an Array
- Return an array of anti-diagonals of given N*N square matrix
- Find determinant of matrix generated by array rotation
- Postfix to Prefix Conversion
- Maximum subarray sum in O(n) using prefix sum
- Maximum prefix-sum for a given range
- Check if matrix can be converted to another matrix by transposing square sub-matrices
- Find the maximum length of the prefix
- Longest Common Prefix using Trie
- Longest Common Prefix Matching | Set-6
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : manishshaw1