1054. Run-Length Reader
A fax archive stores long strips of pixel intensities in compressed form. The array encoding has even length and is read in pairs: encoding[2i] says how many times the intensity encoding[2i+1] repeats. For example [2, 9, 1, 4] stands for the strip 9, 9, 4.
Implement RunLengthReader. A call next(n) consumes the next n pixels of the decoded strip and returns the intensity of the last pixel consumed. If fewer than n pixels remain, the reader consumes everything that is left and returns -1. The decoded strip can be far too long to build, so work directly on the pairs; the total work over all calls must be O(encoding.length + number of calls).
Example 1
- Input:
- operations = ["RunLengthReader","next","next","next","next"]arguments = [[[3,8,2,5]],[2],[2],[1],[1]]
- Output:
- [null,8,5,5,-1]
- Explanation:
The stream is 8,8,8,5,5; consuming 2 ends on an 8, consuming 2 more ends on the first 5 (the third 8 and then a 5), the next 1 ends on 5, and the final request finds nothing left.
Example 2
- Input:
- operations = ["RunLengthReader","next","next","next","next"]arguments = [[[0,4,1,9,2,6]],[1],[1],[1],[1]]
- Output:
- [null,9,6,6,-1]
- Explanation:
The run of four 4s has length zero and is ignored, so the stream is 9,6,6 and the fourth request returns -1.
Example 3
- Input:
- operations = ["RunLengthReader","next","next","next"]arguments = [[[1000000000,7]],[999999999],[1],[1]]
- Output:
- [null,7,7,-1]
- Explanation:
A single huge run is consumed in two requests; the last one runs past the end.
Constraints
0 ≤ encoding.length ≤ 1000 and the length is even
0 ≤ encoding[2i] ≤ 109, 0 ≤ encoding[2i+1] ≤ 109
1 ≤ n ≤ 109, at most 1000 calls
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. - Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(encoding.length + calls) amortised
- Space
- O(1) extra