Prefix tables and hashing
A leading zero lets one subtraction recover any half-open range sum. C++ uses the vector header for this snippet.
| Index read | O(1) | Check that the index is in bounds |
| Range sum after preprocessing | O(1) | P[r] − P[l] |
| Build prefix sums | O(n) | Store n + 1 entries |
| Frequency table | Expected O(n) build | Store one key per distinct value |
Python
def prefix(a):
p = [0]
for x in a:
p.append(p[-1] + x)
return pC++
std::vector<long long> prefix(const std::vector<int>& a) {
std::vector<long long> p{0};
for (int x : a) p.push_back(p.back() + x);
return p;
}Java
static long[] prefix(int[] a) {
long[] p = new long[a.length + 1];
for (int i = 0; i < a.length; i++)
p[i + 1] = p[i] + a[i];
return p;
}