MediumArrayHash TablePrefix Sum

Subarray Sum Equals K

LeetCode
1 approach, code in all languages

You are given an integer array nums and an integer k. Return the total number of contiguous subarrays whose elements add up to exactly k.

A subarray is a non-empty slice of consecutive elements. Note that the values may be negative and zero, so a longer subarray does not necessarily have a larger sum, and simply scanning for a growing window will not work.

Example 1

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

Output: 2

The subarrays [1,1] starting at index 0 and [1,1] starting at index 1 both sum to 2.

Example 2

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

Output: 2

The subarray [3] and the subarray [1,2] both sum to 3.

Constraints

  • 1 <= nums.length <= 2 * 10^4
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now