Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Math
Google
Meta
Amazon
Subarray Sum Equals K

Count how many contiguous subarrays sum to a given value k.

Acceptance 64%
Problem Statement

Subarray Sum Equals K

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

A subarray must consist of consecutive elements from the array, and different starting/ending positions count as different subarrays even if they contain the same values.

Your task is to return the total count of such subarrays.

Notes

  • The array may contain positive numbers, negative numbers, and zeros.
  • Because negative values are allowed, a simple fixed sliding window strategy may not work reliably.
  • An efficient solution typically tracks cumulative sums seen so far.

Input Format

  • nums: an integer array
  • k: an integer target sum

You may assume the input is well-formed and non-empty unless otherwise stated by the platform version of the problem.

Output Format

Return an integer representing the number of contiguous subarrays whose sum equals k.

Constraints

  • The array can contain negative numbers and zeros.
  • Count every valid subarray occurrence.
  • Aim for better than O(n2)O(n^2) if possible.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1, 1, 1], k = 2

Output

2

Explanation

The valid subarrays are [1, 1] starting at index 0 and [1, 1] starting at index 1.

Example 2

Input

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

Output

2

Explanation

The valid subarrays are [1, 2] and [3].

Show 1 more example

Example 3

Input

nums = [1, -1, 0], k = 0

Output

3

Explanation

The valid subarrays are [1, -1], [0], and [1, -1, 0].

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.