DSA interview question
A trading desk records the daily profit or loss of a strategy, which can be positive, negative or zero, and risk management asks for the longest run of consecutive days whose net result is exactly K. The sliding window from the positive-only version breaks here: with negative values, a window whose sum is too large can come back down later, so shrinking it early can skip the answer. The robust technique is prefix sums with a hash map. A subarray (j, i] sums to K exactly when prefix[i] − prefix[j] = K, so for each position you look up whether prefix − K has appeared before, and where it first appeared.
Example: [1, -1, 5, -2, 3], K = 3 → 4 (the subarray [1, -1, 5, -2]).
int longestSubarrayWithSumK(const vector<int>& a, long long k); // any integers; 0 if none
Input (a, k) | Output | Explanation |
|---|---|---|
([1, -1, 5, -2, 3], 3) | 4 | [1, -1, 5, -2] |
([-2, -1, 2, 1], 1) | 2 | [-1, 2] |
([10, 5, 2, 7, 1, 9], 15) | 4 | [5, 2, 7, 1] |
([1, 2, 3], 7) | 0 | No subarray sums to 7 |
([0, 0, 0], 0) | 3 | Zeros extend the answer |
([2, 0, 0, 3], 3) | 3 | [0, 0, 3]: keep the first occurrence of each prefix sum |
(Confirm: values can be negative, zero or positive; return the length, or 0 if no subarray sums to K.)
prefix == K separately?"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