Skip to content

370. Range Addition 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {
    vector<int> ans;
    vector<int> line(length);
    int prefix = 0;

    for (const vector<int>& update : updates) {
      const int start = update[0];
      const int end = update[1];
      const int inc = update[2];
      line[start] += inc;
      if (end + 1 < length)
        line[end + 1] -= inc;
    }

    for (const int diff : line) {
      prefix += diff;
      ans.push_back(prefix);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int[] getModifiedArray(int length, int[][] updates) {
    int[] ans = new int[length];
    int[] line = new int[length];
    int prefix = 0;

    for (int[] update : updates) {
      final int startIndex = update[0];
      final int endIndex = update[1];
      final int inc = update[2];
      line[startIndex] += inc;
      if (endIndex + 1 < length)
        line[endIndex + 1] -= inc;
    }

    for (int i = 0; i < length; ++i) {
      prefix += line[i];
      ans[i] = prefix;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def getModifiedArray(
      self,
      length: int,
      updates: list[list[int]],
  ) -> list[int]:
    line = [0] * length

    for start, end, inc in updates:
      line[start] += inc
      if end + 1 < length:
        line[end + 1] -= inc

    return itertools.accumulate(line)