Subarray Sum Equals K
Track prefix sum frequencies to count subarrays summing to K in O(n).
Problem Statement
Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.
Examples
Example 1
Explanation: Subarrays [1,1] (indices 0-1) and [1,1] (indices 1-2) both sum to 2.
Example 2
Constraints
- 1 ≤ nums.length ≤ 2 × 10⁴
- -1000 ≤ nums[i] ≤ 1000
- -10⁷ ≤ k ≤ 10⁷
Solutions
For every (i,j) pair, compute the subarray sum and count those equal to k. O(n²).
Related Concepts
Deepen your understanding with these related topics from our AI Glossary:
Want to master the core concepts?
Our free AI Glossary covers 190+ topics — from Prefix Sum to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.
Stuck? Ask AI to explain it step by step.
Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.
Free to start · No credit card required to explore
Get Started Free