Algorithms Playbook
← All problems
MediumPrefix sums →Similar to: Subarray Sum Equals K

Slices that add to k

Problem

Given an integer array nums (it may contain negative numbers) and an integer k, return the number of contiguous subarrays whose elements sum to k.

Examples

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

Output: 2

[1, 2] and [3].

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

Output: 3

Hints

    Try it first. Every hint reveals a bit more.

    Solution