Now count how many contiguous subarrays sum to a target k. The running prefix sum plus a hashmap of prefix-count solves it in one pass.
Write subarray_sum_equals_k(nums, k):
This must work with negative numbers, which is why sliding windows do not apply.
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):
"""Count contiguous subarrays whose sum equals k."""
# TODO: running prefix sum + dict of prefix counts seeded {0: 1}
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Now count how many contiguous subarrays sum to a target k. The running prefix sum plus a hashmap of prefix-count solves it in one pass.
Write subarray_sum_equals_k(nums, k):
This must work with negative numbers, which is why sliding windows do not apply.
Press Run Tests or ββ© to check your solution.