Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Subarray Sum Equals K

Hash Mapsmedium

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 124: Maps: Fundamentals

Implement `subarraySumCount(nums, k)` returning the number of contiguous subarrays summing to `k`, using prefix sums and a hash map.

Sample tests

Input: subarraySumCount([1,1,1], 2)
Output: 2
Input: subarraySumCount([1,2,3], 3)
Output: 2

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Forgetting to seed the map with prefix sum 0 counts misses subarrays starting at index 0.

Learning resources

  • Wikipedia: Data structure
Approach & explanation (try first)

Counting prefix sums in a map turns the O(n^2) scan into a single O(n) pass.

Loading...
⌘/Ctrl + Enter

Run your code to see results.