Skip to main content
medium

Subarray Sum Equals K

Your account balance moves a little every day. nums holds the change for each day: a deposit is positive, a withdrawal is negative, and a quiet day is 0. Count the runs of consecutive days whose changes add up to exactly k. Runs may overlap, and a single day is a run on its own. Return how many runs there are. Limits: 1 <= nums.length <= 400000, -1000 <= nums[i] <= 1000, -10000000 <= k <= 10000000. The answer always fits in a 32-bit int. Think about: with withdrawals in the mix, a longer run can add up to less than a shorter one that sits inside it. Example (changes 2, 1, -1, 3, -3, 3 with k = 3): days 1-2: 2 + 1 = 3 days 2-4: 1 - 1 + 3 = 3 days 2-6: 1 - 1 + 3 - 3 + 3 = 3 day 4 alone: 3 days 4-6: 3 - 3 + 3 = 3 day 6 alone: 3 answer: 6

You're watching an account's daily ups and downs and counting the runs of consecutive days that add up to exactly a target. Interviewers like it because the sliding window you reach for first breaks the moment a withdrawal shows up. The classic trap is missing the runs that start on day one. Expect up to 400,000 days, each change from -1000 to 1000, a target from -10,000,000 to 10,000,000, and an answer that fits in a 32-bit int.

Examples

You write

subarray_sum(nums: List[int], k: int)

  1. Example 1

    Input
    nums = [2,1,-1,3,-3,3], k = 3
    returns
    6
  2. Example 2

    Input
    nums = [7], k = 7
    returns
    1

Save this for your laptop

The editor and Run need a bigger screen. The link opens Subarray Sum Equals K ready to code. It is free, and the editor needs no account.

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 126 Arrays & Hashing problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit, and to talk with her for one hour. After that, talking comes with the $79 pack. Anyone can open the editor and run their code.

1Subarray Sum Equals Kmedium
Based onLeetCode

Get a note when something new lands

New company guides, new problems and big changes to Coco. Rare, and you can leave any time. By joining you agree to get these emails.