Range Addition with a Difference Array

medium Arrays

Problem

An array of n zeros is given. Then k updates come, each is l r v: add v to every element from index l to index r (0-based, both included). Print the final array after all updates. Input: the first line is n, and then one update per line.

Constraints

  • 1 <= n <= 10^5
  • 1 <= k <= 10^5

Examples

Input

5
1 3 2
2 4 3
0 2 -2

Output

-2 0 3 5 3

Solutions

Best approachTime O(n + k)Space O(n)

Each update touches only two cells of the difference array: +v at l and -v after r. At the end, one running sum rebuilds the array. The cost is O(n + k) instead of O(n k).

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Apply the updates.
 * Input   : n and the updates.
 * Output  : The final array.
 * Approach: Difference array
 * Time    : O(n + k)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int[] solve(String[] lines) {
        int n = Integer.parseInt(lines[0]);
        // Step 1: diff[i] says how much the value changes when we go from index i - 1 to index i.
        int[] diff = new int[n + 1];
        for (int i = 1; i < lines.length; i++) {
            String[] part = lines[i].split(" ");
            int left = Integer.parseInt(part[0]);
            int right = Integer.parseInt(part[1]);
            int value = Integer.parseInt(part[2]);
            // Step 2: An update changes only two places: it starts at left and stops after right.
            diff[left] += value;
            diff[right + 1] -= value;
        }
        // Step 3: A running sum of diff gives the real array.
        int[] result = new int[n];
        int running = 0;
        for (int i = 0; i < n; i++) {
            running += diff[i];
            result[i] = running;
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        java.util.List<String> all = new java.util.ArrayList<>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            if (!line.isEmpty()) {
                all.add(line);
            }
        }
        String[] lines = all.toArray(new String[0]);
        System.out.println(Arrays.stream(solve(lines)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
    }
}
Hints (1)
  1. Why does -v after r stop the update?