Skip to content
BytePatterns

Subarrays Summing To K

MediumHash Tables#prefix-sums#hash-map~30m

Problem

Given a list of integers and a target k, count how many contiguous stretches of the list add up to exactly k. Stretches that start or end at different positions count separately even when they hold the same values. Negative numbers are allowed, so sums do not grow steadily as the stretch widens.

Examples

Input:  nums = [1, 2, 3, 1], k = 3
Output: 2
Why:    the stretches 1,2 and 3 both total 3
Input:  nums = [2, -1, 2, -1], k = 1
Output: 3
Why:    negatives let several different stretches land on the same total
Input:  nums = [0, 0], k = 0
Output: 3
Why:    edge case, each single zero counts and so does the pair

Hints

0 / 3

Stuck on the idea rather than the code? Prefix Sums covers it.