📚Many Range Queries!
Daily visitors: [5, 8, 6, 3, 7, 9, 4] Librarians ask "sum of day l~r?" dozens of times a day. Re-summing each time is too slow!
Loading...
Daily visitors: [5, 8, 6, 3, 7, 9, 4] Librarians ask "sum of day l~r?" dozens of times a day. Re-summing each time is too slow!
You manage a neighborhood library. You are given an array of daily visitor counts, and librarians repeatedly ask "how many people came from day l to day r?" dozens of times a day. Re-summing from the start for every question is too slow. By precomputing a prefix sum array, you can answer any range with a single subtraction.
visitors = [5, 8, 6, 3, 7, 9, 4], queries = [[2, 5], [0, 2], [4, 6]]
[25, 19, 20]
Prefix: prefix = [0, 5, 13, 19, 22, 29, 38, 42] • [2, 5]: prefix[6] - prefix[2] = 38 - 13 = 25 (6+3+7+9) • [0, 2]: prefix[3] - prefix[0] = 19 - 0 = 19 (5+8+6) • [4, 6]: prefix[7] - prefix[4] = 42 - 22 = 20 (7+9+4)
visitors = [10, 0, 4, 6], queries = [[0, 3], [1, 1]]
[20, 0]
Prefix: prefix = [0, 10, 10, 14, 20] • [0, 3]: prefix[4] - prefix[0] = 20 - 0 = 20 (whole sum) • [1, 1]: prefix[2] - prefix[1] = 10 - 10 = 0 (closed day!)