![]() |
VOOZH | about |
In many grid-based problems, we are asked to perform multiple updates on rectangular submatrices of a 2D array. A direct approach would be to iterate over each cell within the rectangle for every update, which leads to a time complexity of O(k × n × m) for k updates too slow for large inputs.
To handle such cases efficiently, we use a technique called the 2D Difference Array. It is an extension of the 1D difference array, designed for grids. Instead of updating every cell in a submatrix individually, we update just four corners in a helper matrix. Later, we reconstruct the final values using prefix sums.
This allows each range update to be applied in constant time, and the final matrix to be computed in O(n × m) time.
Table of Content
To update a submatrix from (r1, c1) to (r2, c2) with a value v, we use a helper matrix diff[][] instead of updating every cell.
We perform these 4 operations in constant time:
Then, we compute prefix sums over diff[][] to get the final matrix. Only the target submatrix reflects the added value fast and efficient.
Example:
Given a 2D integer matrix mat[][] and a list of operations opr[][]. Each operation is represented as a list of the form [v, r1, c1, r2, c2], where:
Return the final matrix after all operations.
Step By Step Implementations:
Illustrations:
3 4 3 2 2 -1 3 -3 1
Time Complexity
Auxiliary Space
The 2D difference array is a powerful technique for efficiently handling repeated updates to rectangular regions within a matrix. It’s particularly useful in scenarios like:
Instead of looping through every cell in each rectangle which is inefficient on large grids the 2D difference array lets you apply each update in O(1) time by marking only the rectangle’s boundaries. Once all updates are recorded, the final matrix is computed in O(n × m) time using prefix sums, making it ideal for high-performance, large-scale matrix operations.
Let’s analyze the effect:
This ensures that: