#560MediumPrefix Sum

Subarray Sum Equals K

Track prefix sum frequencies to count subarrays summing to K in O(n).

FacebookGoogleAmazonUberOracle

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

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

Explanation: Subarrays [1,1] (indices 0-1) and [1,1] (indices 1-2) both sum to 2.

Example 2

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

Constraints

  • 1 ≤ nums.length ≤ 2 × 10⁴
  • -1000 ≤ nums[i] ≤ 1000
  • -10⁷ ≤ k ≤ 10⁷

Solutions

1
Brute Force — All subarrays
TimeO(n²)SpaceO(1)

For every (i,j) pair, compute the subarray sum and count those equal to k. O(n²).

Visual Animation
def subarraySum(nums: list[int], k: int) -> int:
    count = 0
    for i in range(len(nums)):
        total = 0
        for j in range(i, len(nums)):
            total += nums[j]
            if total == k: count += 1
    return count

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

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.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

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
Back to all problems