# LeetCode – Range Addition (Java)

Assume you have an array of length n initialized with all 0's and are given k update operations.

Each operation is represented as a triplet: [startIndex, endIndex, inc] which increments each element of subarray A[startIndex ... endIndex] (startIndex and endIndex inclusive) with inc.

Return the modified array after all k operations were executed.

For example,
Input: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
Output: [-2,0,3,5,3]

Java Solution 1 - heap

 public int[] getModifiedArray(int length, int[][] updates) { int result[] = new int[length]; if(updates==null || updates.length==0) return result;   //sort updates by starting index Arrays.sort(updates, new Comparator(){ public int compare(int[] a, int [] b){ return a[0]-b[0]; } });   ArrayList list = new ArrayList();   //create a heap sorted by ending index PriorityQueue queue = new PriorityQueue(new Comparator(){ public int compare(Integer a, Integer b){ return updates[a][1]-updates[b][1]; } });   int sum=0; int j=0; for(int i=0; i

Time complexity is O(nlog(n)).

Java Solution 2

We can track each range's start and end when iterating over the ranges. And in the final result array, adjust the values on the change points. The following shows an example:

 public int[] getModifiedArray(int length, int[][] updates) { int[] result = new int[length]; if(updates==null||updates.length==0) return result;   for(int i=0; i

Time complexity is O(n).

Category >> Algorithms
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code>
String foo = "bar";
</code></pre>
• Rachit Pant