Efficient 2D Range Increment Queries Using Difference Arrays
Complexity
Time complexity:
Processing Queries → O(Q)
Prefix Sum Computation → O(n²)
Total: O(n² + Q), much faster than O(Q * n²) naive approach.

Space complex
# Complexity
- Time complexity:
- Processing Queries → O(Q)
- Prefix Sum Computation → O(n²) 
  Total: O(n² + Q), much faster than O(Q * n²) naive approach.
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity:
- O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```java []
class Solution {
    public int[][] rangeAddQueries(int n, int[][] queries) {
        // res starts as an n × n matrix of zeros.
        int[][] res = new int[n][n];

        // Each query [r0, c0, r1, c1] means:
        // Increment res[r0][c0] by +1 (starting point).
        // Decrement res[r0][c1 + 1] by -1 (end column to cancel effect).
        // Decrement res[r1 + 1][c0] by -1 (end row to cancel effect).
        // Increment res[r1 + 1][c1 + 1] by +1 (bottom-right to restore balance).
        for(var q : queries){
            int r0 = q[0], c0 = q[1], r1 = q[2]+1, c1 = q[3]+1;
            res[r0][c0]++;
            if(c1 < n) res[r0][c1]--;
            if(r1 < n){
                res[r1][c0]--;
                if(c1 < n) res[r1][c1]++;
            }
        }

        // Compute Horizontal Prefix Sum
        for(int i=0; i<n; i++){
            for(int j=1; j<n; j++){
                res[i][j] += res[i][j-1];
            }
        }

        // Compute Vertical Prefix Sum
        for(int i=1; i<n; i++){
            for(int j=0; j<n; j++){
                res[i][j] += res[i-1][j];
            }
        }
        return res;
    }
}
```
['Java']