DSA interview question
A fraud-detection team looks at a customer's sequence of transactions (credits and debits, positive and negative) and flags every contiguous stretch whose net total is exactly K, a pattern associated with a known scam. They need the number of such stretches, not just the longest one. With negative values the sliding window doesn't apply, and checking every subarray is O(n²). Prefix sums with a hash map of counts give O(n): each earlier prefix equal to prefix − K marks one subarray ending here.
Example: [1, 1, 1], K = 2 → 2 (the subarrays at indices 0–1 and 1–2).
int subarraySum(const vector<int>& nums, int k); // number of contiguous subarrays with sum k
Input (nums, k) | Output | Explanation |
|---|---|---|
([1, 1, 1], 2) | 2 | |
([1, 2, 3], 3) | 2 | [1, 2] and [3] |
([3, 4, 7, 2, -3, 1, 4, 2], 7) | 4 | [3, 4], [7], [7, 2, -3, 1], [1, 4, 2] |
([1, -1, 0], 0) | 3 | [1, -1], [1, -1, 0], [0] |
([0, 0, 0], 0) | 6 | Every subarray |
([5], 3) | 0 |
(Confirm: values can be negative or zero; count every (start, end) pair whose subarray sums to k.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in