DSA interview question
An accounting audit scans a ledger of daily net movements (positive and negative) looking for the longest stretch of consecutive days where the books exactly balance, meaning the movements sum to zero. That's the "longest subarray with sum K" problem with K = 0, and it has a particularly clean interpretation: a subarray sums to zero exactly when the running total at its end equals the running total just before its start. So you're looking for the two furthest-apart positions with the same prefix sum.
Example: [15, -2, 2, -8, 1, 7, 10, 23] → 5 (the subarray [-2, 2, -8, 1, 7]).
int maxLenZeroSum(const vector<int>& a); // length of the longest subarray with sum 0, or 0
Input a | Output | Explanation |
|---|---|---|
[15, -2, 2, -8, 1, 7, 10, 23] | 5 | [-2, 2, -8, 1, 7] |
[1, 2, 3] | 0 | No zero-sum subarray |
[1, 0, 3] | 1 | [0] |
[0, 0, 0] | 3 | The whole array |
[-1, 1, -1, 1] | 4 | The whole array |
(Confirm: values can be negative, zero or positive; return 0 if no subarray sums to 0.)
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