Skip to content

Instantly share code, notes, and snippets.

@ishank-katiyar
Last active July 28, 2021 05:47
Show Gist options
  • Save ishank-katiyar/1b40f5bc291bc3ffed6db2f2af89d7d5 to your computer and use it in GitHub Desktop.
Save ishank-katiyar/1b40f5bc291bc3ffed6db2f2af89d7d5 to your computer and use it in GitHub Desktop.
difference array technique implementation
/**
* @param a - initial array
* @param query - query array - [li, ri, xi], li and ri are zero-based indexed
* @return array after processing all queries
*/
vector<int> HandleRangeUpdateQuery (vector<int> a, vector<vector<int>> query) {
// creating another array to handle queries
vector<int> b (a.size() + 1, 0);
for (auto& q : query) {
int l = q[0], r = q[1], x = q[2];
// handling query
b[l] += x;
b[r + 1] -= x;
}
// calculating prefix sum of the array b
for (int i = 1; i < b.size() - 1; i += 1) {
b[i] += b[i - 1];
}
// adding all updates back to original array a
for (int i = 0; i < a.size(); i += 1) {
a[i] += b[i];
}
return a;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment