You are given an integer length and an array updates where updates[i] = [startIdxi, endIdxi, inci].
You have an array arr of length length with all zeros, and you have some operation to apply on arr. In the ith operation, you should increment all the elements arr[startIdxi], arr[startIdxi + 1], ..., arr[endIdxi] by inci.
publicclassSolution {
publicint[]getModifiedArray(int length, int[][] updates) {
int[] result =newint[length];
if (updates ==null|| updates.length== 0) {
return result;
}
// Sort updates by starting index Arrays.sort(updates, Comparator.comparingInt(a -> a[0]));
// Create a heap sorted by ending index PriorityQueue<Integer> queue =new PriorityQueue<>(Comparator.comparingInt(a -> updates[a][1]));
int sum = 0;
int j = 0;
for (int i = 0; i < length; i++) {
// Subtract value from sum when ending index is reachedwhile (!queue.isEmpty() && updates[queue.peek()][1]< i) {
int top = queue.poll();
sum -= updates[top][2];
}
// Add value to sum when starting index is reachedwhile (j < updates.length&& updates[j][0]<= i) {
sum += updates[j][2];
queue.offer(j);
j++;
}
result[i]= sum;
}
return result;
}
}
⏰ Time complexity: O(n log m), where n is the length of the array and m is the number of updates. Sorting the updates costs O(m log m) and each element is processed through the heap operations, costing O(n log m) in total.
🧺 Space complexity: O(m), due to the space used by the heap to store the indices of the updates being processed.
⏰ Time complexity: O(n + m), , where n is the length of arr and m is the number of updates. This is because we iterate over the updates once and then compute the prefix sum in another pass.
🧺 Space complexity: O(1), extra space (excluding the input and output arrays).