Explained Step By Step | 1D Prefix Sum approach | Simple and Easy to understand
\n// How do we add a number in a 1D array for range i to j?\n// We increase arr[i] by X and decrease arr[j+1] by X\n// Why do we do so?\n// We do so because whe
```\n// How do we add a number in a 1D array for range i to j?\n// We increase arr[i] by X and decrease arr[j+1] by X\n// Why do we do so?\n// We do so because when we sum the array from (i+1) till j then elements in the range i to j is increased and arr[j+1] becomes neuteral hence array from range i to j is increased by x\n// For Ex:- \n// arr[] = {0, 0, 0, 0, 0, 0}\n// increase the array by X for range 1 to 3\n// add arr[1] by X and subtract arr[4] by X\n// arr[] = {0, X, 0, 0, -X, 0}\n// after performing sum arr[] = {0, X, X, X, 0, 0}\n\n// We will be using the same approach for each row starting from row1 to row2 for each query in queries\n// We will perform sum row-wise to increase the matrix\n// finally, return the matrix\n\nclass Solution {\n    public int[][] rangeAddQueries(int n, int[][] queries) {\n        \n        int[][] mat = new int[n][n];\n        \n        for(int[] query : queries) {\n            \n            int row1 = query[0], col1 = query[1], row2 = query[2], col2 = query[3];\n            \n            while(row1 <= row2) {\n                mat[row1][col1]++;\n                if(col2 + 1 < n) {\n                    mat[row1][col2+1]--;\n                }\n                ++row1;\n            }\n        }\n        \n        for(int i = 0; i < n; i++) {\n            for(int j = 1; j < n; j++) {\n                mat[i][j] += mat[i][j-1];\n            }\n        }\n        \n        return mat;\n    }\n}\n```\n**Please upvote\uD83D\uDC4D if you find it useful**
['Prefix Sum', 'Java']