InferenceAI

Enter at least two characters to search.

Start free

Count Subarrays Summing to K

mediumArrays & Hashing25 min25 XP

Return the number of contiguous subarrays of nums whose sum equals k. Values may be negative.

Requirements

  • O(n)O(n) with a hash map of prefix-sum counts.

Examples

EXAMPLE WALKTHROUGHoverlapping

A guided view of the published example, not a trace of your code.

INPUT[[1,1,1],2]
TASKsubarray_sums_to_k()
EXPECTED OUTPUT2

Start with the input values shown in this example.

Example 1 of 3

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

Output: 2

Explanation: overlapping

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

Output: 2

Explanation: two ways

Input: nums = [1,-1,0], k = 0

Output: 3

Explanation: with negatives

Hint 1

Each earlier prefix equal to (current prefix - k) marks one valid subarray ending here.

Topics

DSAArrays & HashingPython