Answer half-open range queries
Difficulty: Easy
Try your first run
No account is needed to try this exercise. Write your answer, run the tests, and use the feedback to improve it.
- Read the examples and the required return value.
- Edit the supplied function in the editor, keeping its name and parameters. Return your answer, then select Run code.
- Use the test feedback to try again. Hints are available without replacing your code.
For each [start,end] return sum(values[start:end]). Queries obey 0 <= start <= end <= n.
Examples
[2, -1, 4], [[0, 3], [1, 1], [1, 3]][5, 0, 3][], [[0, 0]][0][3], [][]Constraints
Use the stated representation and return value. Do not mutate inputs. Unless a tighter limit is stated, arrays contain at most 200 integers in -1000..1000; graphs have at most 100 vertices, valid indices and 1000 edges; tree depth is at most 30. No network or file access. Tests support learning; review the implementation to check the requested algorithm.
Review lesson: Arrays and prefix computationsA little nudge
Reveal one hint at a time. Give yourself a moment to try it.
- Write down the empty-input or smallest valid result before the general case.
- Subtract the prefix before the interval from the prefix after it.
- Trace the working state on the first example and check the stated tie/order rule.
Worked solution
Try your own approach first, then compare the reasoning.
function solve(values, queries) { const p=[0]; for(const v of values) p.push(p[p.length-1]+v); return queries.map(([a,b])=>p[b]-p[a]); }
Subtract the prefix before the interval from the prefix after it.
Complexity
O(n+q) time and space for q queries.
Ready when you are
Write your solution, then run it against the practice tests.
Press Esc, then Tab to leave the editor. Code runs in an isolated browser workspace. Tests support learning, not verified grading.