Skip to content

Subarrays equals K ​

Subarrays equals K — LeetCode

Given an array and an integer k, count the number of contiguous subarrays whose elements sum to exactly k.

Approach ​

Prefix sum + Counting method. Bit complicated.

Go through summing the array. At each point, check what prefix can be removed to get k. Check if that k has occurred in prefixSums, and the count of occurrence. res += count.

Remarks ​

https://youtu.be/fFVZt-6sgyo?si=9hmDzEURjuh4TKHz