ASAPUtils Logo ASAPUtils
Week 2

Subarray Sum Equals K

Subarray Sum Equals K with prefix sums and a hash map, with C++ and JavaScript solutions, a visualizer, and a clear explanation of why a sliding window is the wrong tool once negatives appear.

medium Arrays Prefix Sums O(n) time · O(n) space Open on LeetCode ↗

The problem

Given an integer array and an integer k, return the total number of contiguous subarrays whose elements sum to k. The array may contain negative numbers.

nums = [1, 2, 3, -2, 2], k = 3 -> 4 ([1,2], [3], [2,3,-2], [3,-2,2])

Related Problems