Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Arrays and hashing

Count subarrays with a given sum

Medium · Target 20 minutes · Arrays and hashing· Type asked at

Given an array nums of integers, which may be negative, and an integer k, return the number of contiguous subarrays whose elements sum to exactly k.

Subarrays are counted by position, so two subarrays covering different index ranges count separately even if they hold the same values.

Examples

InputOutputWhy
nums = [1, 1, 1], k = 22Indices 0–1 and 1–2.
nums = [3, 4, 7, 2, -3, 1, 4, 2], k = 74[3,4], [7], [7,2,-3,1], [1,4,2]. The negative value is why a window does not work.
nums = [1, -1, 0], k = 03[1,-1], [1,-1,0] and [0].

Constraints

  • 1 ≤ n ≤ 2 × 10⁴
  • −1000 ≤ nums[i] ≤ 1000
  • −10⁷ ≤ k ≤ 10⁷
  • Values may be negative or zero

Hints

Hint 1

A sliding window needs the sum to grow as the window grows. Check whether that holds when the array contains negative numbers.

Hint 2

Let P[i] be the sum of the first i elements. The sum of the range (i, j] is P[j] − P[i]. Rewrite the condition you want in terms of P.

Hint 3

You need P[j] − P[i] = k, so P[i] = P[j] − k. Sweep j, and at each step ask how many earlier prefixes had the value P[j] − k. A hash map of counts answers that in O(1).

Where people lose marks

  • Reaching for a sliding window. It is correct only when every value is non-negative; with a negative number present it silently returns the wrong count.
  • Forgetting to seed the map with {0: 1}. Everything still runs, and every subarray starting at index 0 is missed.
  • Storing a set instead of counts, which collapses repeated prefix values and undercounts.
  • Recording the current prefix in the map before looking up P[j] − k. When k = 0 that counts the empty subarray and inflates the answer. Look up first, then insert.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.