![]() |
VOOZH | about |
In many problems, we’re asked to perform multiple range updates like adding a value to all elements from index l to r. A direct approach updates each element in the range, leading to a time complexity of O(k × n) for k updates, which becomes inefficient for large inputs.
The 1D Difference Array optimizes this by updating only the boundaries of each range in a helper array. After all updates, a prefix sum reconstructs the final array in O(n) time.
This allows each range update to be applied in O(1) time, making it highly efficient for problems involving multiple subarray modifications.
Table of Content
To efficiently handle multiple range updates, we use a helper array called a difference array diff[], initialized with all zeros:
Instead of directly updating every index from l to r, we update only the boundaries:
To add a value v to a range [l, r], we do:
This way, the effect of +v starts at index l and is canceled after index r.
After all operations, we compute the prefix sum of diff[] to propagate the updates across the array:
Finally, apply these changes to the original array:
This approach ensures that each update is applied in O(1), and the final array is constructed in a single pass making it highly efficient for problems with multiple range updates.
Example:
Given an array arr[] and a 2D array opr[][], where each row represents an operation in the form [l, r, v]. For each operation, add v to all elements from index l to r in arr. Return the updated array after applying all operations.
Step By Step Implementations:
i from 1 to n - 1, do:diff[i] += diff[i - 1]Illustrations:
1 12 8 9 0
Time Complexity:
Auxiliary Space:
Instead of directly updating every element between l and r for each operation (which takes O(r − l + 1) time), we use a smarter trick with a difference array diff[].
Think of it like placing flags:
You don’t update every element between l and r right away.
You just mark where the effect starts and ends in the diff[] array.
After applying all such operations, you build the final result using a prefix sum:
This way, each element of the array gets all the updates it should, without updating each one manually per operation.
So instead of O(m × n) for m operations, the total time becomes just O(m + n).
In the previous implementation, we used an extra array (diff[]) to track range updates and another result array to store the final output. But if memory is a concern, and you're allowed to modify the original array, you can implement the same logic in-place without using any extra space.
How it Works
To save extra space, we modify the input array arr itself to behave like a difference array. Here's the step-by-step idea:
arr into a difference array without using extra space.1 12 8 9 0
Why Right-to-Left?
-> We subtract arr[i - 1] from arr[i] to build the difference array. Doing this from right to left ensures we don’t overwrite values (arr[i - 1]) before they're used preventing incorrect results.