Prefix sums have a dual: the difference array. It applies many range updates cheaply and materializes the final array with one prefix pass. Great for batched increments in analytics.
Build a class DiffArray:
Handle overlapping range updates correctly.
class RangeSum:
def __init__(self, nums):
self.prefix = [0]
for x in nums:
self.prefix.append(self.prefix[-1] + x)
def query(self, i, j):
return self.prefix[j + 1] - self.prefix[i]
def subarray_sum_equals_k(nums, k):
counts = {0: 1}
running = 0
total = 0
for x in nums:
running += x
total += counts.get(running - k, 0)
counts[running] = counts.get(running, 0) + 1
return total
class DiffArray:
def __init__(self, n):
"""Start a length-n logical array of zeros."""
# TODO: keep an internal diff list of size n + 1
pass
def add(self, i, j, delta):
"""Add delta to every index in [i, j]."""
# TODO: diff[i] += delta and diff[j + 1] -= delta
pass
def result(self):
"""Materialize the final array via a prefix sum of diff."""
# TODO: running prefix sum over the first n diff entries
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Prefix sums have a dual: the difference array. It applies many range updates cheaply and materializes the final array with one prefix pass. Great for batched increments in analytics.
Build a class DiffArray:
Handle overlapping range updates correctly.
Press Run Tests or ββ© to check your solution.