Arrays and prefix sums

Find the sum of the supplied zero-based interval. Include both endpoints.

Examples

Example 1

Input
[3, 5, 2, 7], left = 1, right = 2
Expected output
7

Example 2

Input
[3, 5, 2, 7], left = 0, right = 0
Expected output
3

Hints and solution

Hint 1

Build [0, 3, 8, 10, 17] as the prefix for this input.

Reveal worked answer

To sum indices 1 through 2, take the sum of the first three entries and subtract the sum of the first one. That is 10 − 3 = 7. The single index 0 uses 3 − 0 = 3.

Back to the lesson