oneby7

Arrays and Hashing Prefix sums

74. Subarray Sum Equals K

Medium 147 DSA Sheet

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

A subarray is a contiguous sequence of elements from nums. Two subarrays are different if they start or end at different positions.

Example 1

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

Output: 4

Explanation: Four subarrays add up to 3: [3], [-1, 3, 1], [1, -2, 4] and the first five elements [2, -1, 3, 1, -2].

Example 2

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

Output: 3

Explanation: Every pair of neighbours adds up to 2, and there are three pairs, at positions 0–1, 1–2 and 2–3.

Example 3

Input: nums = [5, -5, 5], k = 0

Output: 2

Explanation: [5, -5] and [-5, 5] both add up to 0. A single element is never 0 here, and the whole array adds up to 5.

Check your understanding

Work out the answer for this input before you write any code.

nums = [0, 0, 0], k = 0

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • -109 ≤ k ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.