Challenge: Range Sum Questions
Completed
Read a list of numbers, then q questions. Each question gives i j: print the sum of the items from index i to j (both included, starting at 0). Use a prefix sum list.
Input
Line 1: whole numbers. Line 2: q. Then q lines with i j.
Output
One total per question.
Example
Input
5 2 7 1 4 3 1 3 0 4 2 2
Output
10 19 7
Editor
Python
Hints
prefix[0] = 0 and prefix[i + 1] = prefix[i] + nums[i].
sum(i..j) = prefix[j + 1] - prefix[i].
Solution explanation
Building the prefix list is O(n); then every question is answered in O(1).
Show solution
nums = list(map(int, input().split()))
prefix = [0]
for x in nums:
prefix.append(prefix[-1] + x)
q = int(input())
for _ in range(q):
i, j = map(int, input().split())
print(prefix[j + 1] - prefix[i]) Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module