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
class Solution {
 public:
  vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {
    vector<int> ans(length);
    int prefix = 0;

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

    for (int i = 0; i < length; ++i) {
      prefix += ans[i];
      ans[i] = 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
class Solution {
  public int[] getModifiedArray(int length, int[][] updates) {
    int[] ans = 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];
      ans[startIndex] += inc;
      if (endIndex + 1 < length)
        ans[endIndex + 1] -= inc;
    }

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

    return ans;
  }
}
Back to top