PPractick

DSA interview question

Largest Subarray with Sum 0

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

The problem

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

Function signature

int maxLenZeroSum(const vector<int>& a);  // length of the longest subarray with sum 0, or 0

Test cases

Input aOutputExplanation
[15, -2, 2, -8, 1, 7, 10, 23]5[-2, 2, -8, 1, 7]
[1, 2, 3]0No zero-sum subarray
[1, 0, 3]1[0]
[0, 0, 0]3The whole array
[-1, 1, -1, 1]4The whole array

(Confirm: values can be negative, zero or positive; return 0 if no subarray sums to 0.)

How interviewers phrase it

Clarifying questions to ask

  1. Can values be negative or zero?
  2. Length or the subarray itself?
  3. What if there is no such subarray?

Follow-ups to expect

  1. "Why do equal prefix sums mean a zero-sum subarray?"
  2. "Why store the first occurrence?"
  3. "How do you include subarrays starting at index 0?"
  4. "How would you just check existence?"
  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