PPractick

DSA interview question

Longest Subarray with Sum K (Any Integers)

Medium · Algorithms · Topics: array, prefix sum, hash map

The problem

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

Function signature

int longestSubarrayWithSumK(const vector<int>& a, long long k);  // any integers; 0 if none

Test cases

Input (a, k)OutputExplanation
([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)0No subarray sums to 7
([0, 0, 0], 0)3Zeros 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.)

How interviewers phrase it

Clarifying questions to ask

  1. Can values be negative or zero?
  2. Return the length or the subarray?
  3. How large can the sums get? (Use 64-bit prefix sums.)

Follow-ups to expect

  1. "Why doesn't the sliding window work?"
  2. "Why store only the first occurrence of each prefix sum?"
  3. "What changes if you want the count instead of the length?"
  4. "Why handle prefix == K separately?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in