Build running totals with a leading zero and join them.
Acceptance criteria
- 1.#out should show 0-3-4-8.
DSA Tutorial · Range Queries
These 10 tasks go with the Prefix Sums and Range Queries chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “If a problem asks the same question about many different ranges, precompute once rather than re-scanning for every query.” .
1.Build a prefix arrayexercise · easy · 10 min
Build running totals with a leading zero and join them.
Passes when: #out should show 0-3-4-8.
2.Sum a rangeexercise · easy · 10 min · practice plan
Use prefix sums to total indices two through five.
Passes when: #out should show sum 19.
3.Whole array totalexercise · easy · 10 min · practice plan
Show the total of every value using the prefix array.
Passes when: #out should show sum 31.
4.Count subarrays with a sumexercise · easy · 10 min · practice plan
Count runs adding to seven using a hash map.
Passes when: #out should show found 4.
5.Updates need a treeexercise · medium · 10 min · practice plan
Report the structure needed when values change between queries.
Passes when: #out should show fenwick tree.
6.Fix the prefix without a leading zerobug fix · easy · 8 min
Starting at the first value makes every range need a special case.
Passes when: #out should show 0-3-4-8.
7.Fix the range bounds off by onebug fix · easy · 8 min · practice plan
The range sum subtracts the prefix before the start, not at it.
Passes when: #out should show sum 19.
8.Fix the counter missing the empty prefixbug fix · medium · 8 min · practice plan
Without seeding zero, runs starting at index zero are never counted.
Passes when: #out should show found 4.
9.Fix the running total recorded firstbug fix · easy · 8 min · practice plan
Storing before looking up lets a run match itself when the target is zero.
Passes when: #out should show found 0.
10.Fix the prefix array used with updatesbug fix · easy · 8 min · practice plan
One change invalidates every later entry, so a tree is needed.
Passes when: #out should show fenwick tree.
Between them these tasks cover Prefix arrays, Range sums and Fenwick trees.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.