Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Arrays and hashing

Count subarrays with a given sum

Medium · Target 20 minutes · Arrays and hashing · Type asked atCitadelTwo SigmaOptiver

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).

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.