Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find matrix for which rows and columns holding sum of behind rows and columns in Python
Given a matrix, we need to find a new matrix where each element at position res[i, j] contains the sum of all elements from the original matrix where row r ? i and column c ? j. This is known as calculating the prefix sum matrix or cumulative sum matrix.
Problem Understanding
For each position (i, j) in the result matrix, we sum all elements in the rectangle from (0, 0) to (i, j) in the original matrix.
If the input matrix is ?
| 8 | 2 |
| 7 | 4 |
Then the output will be ?
| 8 | 10 |
| 15 | 21 |
Algorithm
We solve this in two steps ?
- Row-wise prefix sum: Add the element above to each element
- Column-wise prefix sum: Add the element to the left to each element
Implementation
def solve(matrix):
if not matrix:
return matrix
R, C = len(matrix), len(matrix[0])
# Step 1: Add elements from above (row-wise prefix)
for r in range(1, R):
for c in range(C):
matrix[r][c] += matrix[r - 1][c]
# Step 2: Add elements from left (column-wise prefix)
for r in range(R):
for c in range(1, C):
matrix[r][c] += matrix[r][c - 1]
return matrix
# Test the function
matrix = [
[8, 2],
[7, 4]
]
result = solve(matrix)
print(result)
[[8, 10], [15, 21]]
Step-by-Step Calculation
Let's trace through the algorithm ?
Original Matrix
[8, 2] [7, 4]
After Row-wise Prefix Sum
[8, 2] # First row unchanged [15, 6] # 7+8=15, 4+2=6
After Column-wise Prefix Sum
[8, 10] # 8, 2+8=10 [15, 21] # 15, 6+15=21
Alternative Implementation (Non-destructive)
If you want to preserve the original matrix ?
def solve_preserve_original(matrix):
if not matrix:
return matrix
R, C = len(matrix), len(matrix[0])
result = [[0] * C for _ in range(R)]
# Build prefix sum matrix
for r in range(R):
for c in range(C):
result[r][c] = matrix[r][c]
if r > 0:
result[r][c] += result[r-1][c]
if c > 0:
result[r][c] += result[r][c-1]
if r > 0 and c > 0:
result[r][c] -= result[r-1][c-1] # Avoid double counting
return result
# Test with original matrix preserved
original_matrix = [
[8, 2],
[7, 4]
]
result = solve_preserve_original(original_matrix)
print("Original:", original_matrix)
print("Result:", result)
Original: [[8, 2], [7, 4]] Result: [[8, 10], [15, 21]]
Time and Space Complexity
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| In-place modification | O(R × C) | O(1) |
| Preserve original | O(R × C) | O(R × C) |
Conclusion
The prefix sum matrix can be computed efficiently in O(R × C) time using a two-step approach: first computing row-wise prefix sums, then column-wise prefix sums. This technique is useful in dynamic programming and range query problems.
