Data Structures & AlgorithmsVery hardProduct Company SDE · greedy OA

Problem: What is the maximum number of pairwise non-overlapping non-empty subarrays of [1, -1, 2, -2, 3, -3] each having sum zero? Run the greedy code.

Problem: What is the maximum number of pairwise non-overlapping non-empty subarrays of [1, -1, 2, -2, 3, -3] each having sum zero? Run the greedy code.
a = [1, -1, 2, -2, 3, -3]
seen = {0}
s = 0
cnt = 0
for x in a:
    s += x
    if s in seen:
        cnt += 1
        seen = {0}
        s = 0
    else:
        seen.add(s)
print(cnt)
What is printed?
  1. A. 2
  2. B. 4
  3. C. 3
  4. D. 6

Correct answer: C. 3

Greedily closing a zero-sum block as soon as one is seen gives [1,-1], [2,-2] and [3,-3], which is optimal because the earliest finishing block leaves the most room.

More Coding Interview Problems questions

Exams that ask this topic