DSA interview question
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]).
int longestSubarrayWithSumK(const vector<int>& a, long long k); // a has positive values; 0 if none
Input (a, k) | Output | Explanation |
|---|---|---|
([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) | 0 | No 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.)
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