Loading
Loading
A smart meter records the net energy flow for each interval of the day — positive when the house draws power, negative when its panels export it. An analyst asks many questions of the form: what was the total flow from interval l to interval r?
Given readings and queries, where each query is a pair [l, r] of 0-based indices with l ≤ r, return the total of readings[l..r] inclusive for every query, in order.
readings = [4, -1, 7, 2, 3], queries = [[0, 2], [1, 3], [4, 4]]prefix = [0, 4, 3, 10, 12, 15]prefix[i] = total of the first i readings[0, 2]prefix[3] − prefix[0] = 10[1, 3]prefix[4] − prefix[1] = 8[4, 4]prefix[5] − prefix[4] = 3[10, 8, 3]Sign in to keep a note here. It is free, and nobody else can see it.
Sign inExample 1
Sign in to open hints.
Struggling is where the learning happens. Open this once you have genuinely tried, or once the hints have run out.
O(n + q) time · O(n) space
Input. Run your code to watch it work on this input, one line at a time.
| 0 | 0 | 2 |
|---|---|---|
| 1 | 1 | 3 |
| 2 | 4 | 4 |
Running code is turned off on this deployment. You can still read the problem, write code, use hints and the visualizer.
Tab moves focus out of the editor. Press Ctrl+M to let Tab indent instead.
No results yet
Run your code against the sample tests, or submit to run the full suite.
| 0 | 0 | 2 |
|---|---|---|
| 1 | 1 | 3 |
| 2 | 4 | 4 |
4 + (-1) + 7 = 10, (-1) + 7 + 2 = 8, and the single reading 3.
Example 2
| 0 | 0 | 1 |
|---|---|---|
| 1 | 1 | 1 |