Practice › Arrays
Range Add Queries
Medium · Arrays · Asked at Amazon, Google, Uber
Start with an array of n integers. Each of q updates l r x adds x to every element from position l to r (1-based, inclusive). Print the array after all updates.
Input
First line: n. Second line: n space-separated integers. Third line: q. Next q lines: l r x.
Output
The final array, space-separated.
Constraints
- 1 ≤ n, q ≤ 10^5
- 1 ≤ l ≤ r ≤ n
- −10^9 ≤ a[i] ≤ 10^9
- −10^4 ≤ x ≤ 10^4
Difference array: add x at d[l] and subtract it at d[r + 1]. One prefix sum over d at the end gives every element its total change — O(n + q) instead of O(n × q). Values can pass 2^31, so use 64-bit integers.
Example 1
Input
5 1 2 3 4 5 2 1 3 10 2 5 -1
Output
11 11 12 3 4
Hints
- Updating every element of each range is O(n × q) = 10^10 — too slow.
- Mark only where a range starts and where it ends.
- A prefix sum over those marks gives each element its total change.
Approach
Keep a difference array d of size n + 1. An update (l, r, x) does d[l−1] += x and d[r] −= x (0-based). After all updates, walk left to right with a running sum of d — at index i the running sum is exactly the total added to a[i]. Values reach about 2 × 10^9, so use 64-bit integers.
Complexity: O(n + q) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<long long> a(n), d(n + 1, 0);
for (auto &x : a) cin >> x;
int q;
cin >> q;
while (q--) {
int l, r;
long long x;
cin >> l >> r >> x;
d[l - 1] += x;
d[r] -= x;
}
long long run = 0;
for (int i = 0; i < n; i++) {
run += d[i];
cout << a[i] + run << (i + 1 < n ? ' ' : '\n');
}
return 0;
}Python solution
import sys
data = sys.stdin.buffer.read().split()
n = int(data[0])
a = list(map(int, data[1 : 1 + n]))
q = int(data[1 + n])
d = [0] * (n + 1)
p = 2 + n
for _ in range(q):
l, r, x = int(data[p]), int(data[p + 1]), int(data[p + 2])
p += 3
d[l - 1] += x
d[r] -= x
run = 0
out = []
for i in range(n):
run += d[i]
out.append(a[i] + run)
print(" ".join(map(str, out)))Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
long[] a = new long[n];
long[] d = new long[n + 1];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
in.nextToken();
int q = (int) in.nval;
for (int k = 0; k < q; k++) {
in.nextToken();
int l = (int) in.nval;
in.nextToken();
int r = (int) in.nval;
in.nextToken();
long x = (long) in.nval;
d[l - 1] += x;
d[r] -= x;
}
StringBuilder sb = new StringBuilder();
long run = 0;
for (int i = 0; i < n; i++) {
run += d[i];
sb.append(a[i] + run).append(i + 1 < n ? " " : "\n");
}
System.out.print(sb);
}
}