Difference array
Time O(length + updates) Space O(length)diff[start] += inc; diff[end + 1] −= inc; then running sum.
length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]Step 1/4Update [1,3,+2]: +2 at index 1, −2 at index 4 (just after the end). diff has one extra slot for the stop notes.
class Solution {
public int[] getModifiedArray(int length, int[][] updates) {
int[] diff = new int[length + 1];
for (int[] u : updates) { diff[u[0]] += u[2]; diff[u[1] + 1] -= u[2]; }
int[] out = new int[length];
for (int i = 0, run = 0; i < length; i++) { run += diff[i]; out[i] = run; }
return out;
}
}Verdict: Applying each update directly is O(length × updates).