1247. Zero Sum Watcher
Design a class ZeroSumWatcher that watches a growing sequence of integers, empty at the start. append(x) adds the integer x to the end of the sequence and returns nothing. zeroSumCount() returns, as a long, the number of non-empty contiguous stretches of the current sequence whose sum is exactly 0; stretches at different positions count separately even when they hold the same numbers.
longestZeroSum() returns the length of the longest such stretch, or 0 if there is none. Keep hash maps of prefix-sum counts and of first positions so that every call runs in O(1) time on average, using O(n) space for n appended values.
Example 1
- Input:
- operations = ["ZeroSumWatcher","append","append","append","append","zeroSumCount","longestZeroSum"]arguments = [[],[1],[-1],[2],[-2],[],[]]
- Output:
- [null,null,null,null,null,3,4]
- Explanation:
The zero-sum stretches are [1, -1], [2, -2] and the whole sequence, so the count is 3 and the longest has length 4.
Example 2
- Input:
- operations = ["ZeroSumWatcher","zeroSumCount","longestZeroSum","append","zeroSumCount","longestZeroSum"]arguments = [[],[],[],[0],[],[]]
- Output:
- [null,0,0,null,1,1]
- Explanation:
An empty sequence has no stretches, so both answers are 0; after appending 0 the single element is one stretch of length 1.
Example 3
- Input:
- operations = ["ZeroSumWatcher","append","append","append","append","zeroSumCount","longestZeroSum"]arguments = [[],[3],[-3],[3],[-3],[],[]]
- Output:
- [null,null,null,null,null,4,4]
- Explanation:
The zero-sum stretches are three adjacent pairs plus the whole sequence, so the count is 4 and the longest has length 4.
Constraints
-
at most 2000 calls in total -
-105 ≤ x ≤ 105
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Input
- Each case is an operation log.
operationsnames the class first and then each method call;argumentsholds the arguments for each, in the same order. Your answer is one list with a result per operation -nullfor the constructor and for methods that return nothing.
Expected complexity
- Time
- O(1) per call
- Space
- O(n)