Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count Subarrays with Sum k Using Prefix Hash Map

Count the number of continuous subarrays whose sum equals k using prefix sums and a hash map.

Python practice16 minHashing & SetsIntermediateLast updated March 26, 2026

Problem statement

Given an integer array nums and an integer k, return the number of continuous subarrays whose sum equals to k. Use a hashmap to store prefix sum frequencies: for current prefix sum 'presum', the number of valid subarrays ending at current index equals the frequency of (presum - k).

Task

Apply prefix-sum and hashing to count subarrays summing to k in O(n) time and O(n) space.

Examples

Small example

Input

nums = [1,1,1], k = 2

Output

2

Subarrays [1,1] at indices (0,1) and (1,2).

Input format

An integer list nums and an integer k.

Output format

An integer count of continuous subarrays whose sum equals k.

Constraints

-10^5 <= nums[i] <= 10^5, 0 <= len(nums) <= 10^5. Use O(n) time and O(n) extra space.

Samples

Sample 1

Input

nums = [1,2,3], k = 3

Output

2

Subarrays [1,2] and [3].