PPractick

DSA interview question

Longest Subarray with Sum K (Positive Numbers)

Medium · Algorithms · Topics: array, prefix sum, sliding window

The problem

A delivery driver logs the kilometres covered on each leg of a route, all positive. Head office wants the longest sequence of consecutive legs that adds up to exactly K kilometres, to plan a standard shift. Checking every subarray is O(n²). Because every value is positive, a much faster idea works: a sliding window. Growing the window can only increase its sum and shrinking it can only decrease the sum, so one pass with two pointers finds the answer in O(n).

Example: [1, 2, 3, 1, 1, 1, 1, 4, 2, 3], K = 3 → 3 (the subarray [1, 1, 1]).

Function signature

int longestSubarrayWithSumK(const vector<int>& a, long long k);  // a has positive values; 0 if none

Test cases

Input (a, k)OutputExplanation
([1, 2, 3, 1, 1, 1, 1, 4, 2, 3], 3)3[1, 1, 1] beats [1, 2] and [3]
([10, 5, 2, 7, 1, 9], 15)4[5, 2, 7, 1]
([2, 3, 5], 5)2[2, 3] is longer than [5]
([1, 1, 1, 1], 2)2
([5], 3)0No subarray sums to 3

(Confirm: every value is positive (non-negative also works); return 0 if no subarray has sum K. Arrays with negative numbers need the prefix-sum method in S.No 75.)

How interviewers phrase it

Clarifying questions to ask

  1. Are all the values positive? (That's what makes the sliding window valid.)
  2. Should I return the length or the subarray itself?
  3. What if no subarray matches: return 0?
  4. How large can the sums get? (Use 64-bit.)

Follow-ups to expect

  1. "Why does the sliding window need positive numbers?"
  2. "Why is it O(n) with a nested while loop?"
  3. "What's the brute-force approach?"
  4. "What if there are negative numbers?"
  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