Totals for Many Ranges

EasyRunning Totals≈ 20 min

You are given a list of integers nums and a list of questions, as two lists of the same length, starts and ends. Question i asks for the total of the numbers from index starts[i] to index ends[i], both included.

Return the answers, one per question, in the order the questions are asked.

Examples

text
nums = [3, -1, 4, 1, 5], starts = [0, 1, 4], ends = [2, 3, 4]   →  [6, 4, 5]
nums = [7], starts = [0], ends = [0]                            →  [7]
nums = [1, 2, 3, 4], starts = [0, 0, 3], ends = [3, 0, 3]       →  [10, 1, 4]
nums = [5, 5], starts = [], ends = []                           →  []

In the first example the questions ask for 3 + (−1) + 4 = 6, −1 + 4 + 1 = 4 and 5.

Constraints

  • Between 1 and 10,000 numbers, each between -100,000 and 100,000, and up to 10,000 questions.
  • For every question, 0 ≤ starts[i] ≤ ends[i] < len(nums).
  • Aim for O(n + q), n numbers and q questions: each answer in a constant number of steps.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 7 on the judge, 3 of them hidden, and measures how your solution scales.