Problem
We can use run-length encoding (i.e., RLE) to encode a sequence of integers. In a run-length encoded array of even length encoding
(0-indexed), for all even i
, encoding[i]
tells us the number of times that the non-negative integer value encoding[i + 1]
is repeated in the sequence.
- For example, the sequence
arr = [8,8,8,5,5]
can be encoded to beencoding = [3,8,2,5]
.encoding = [3,8,0,9,2,5]
andencoding = [2,8,1,8,2,5]
are also valid RLE ofarr
.
Given a run-length encoded array, design an iterator that iterates through it.
Implement the RLEIterator
class:
RLEIterator(int[] encoded)
Initializes the object with the encoded arrayencoded
.int next(int n)
Exhausts the nextn
elements and returns the last element exhausted in this way. If there is no element left to exhaust, return-1
instead.
Examples
Example 1:
|
|
Input Format
Java
|
|
Solution
Method 1 - Iterator with Pointer and Consumption
Intuition
We maintain a pointer to the current run in the encoding and a counter for how many elements remain in that run. For each next(n)
call, we consume elements from the current run, moving to the next run as needed, and return the last value exhausted, or -1
if we run out.
Approach
- Store the encoding array and a pointer to the current run (index).
- For each
next(n)
call:- While
n > 0
and there are runs left:- If the current run has enough elements, consume
n
and return the value. - Otherwise, consume all remaining elements in the current run, subtract from
n
, and move to the next run.
- If the current run has enough elements, consume
- While
- If we run out of runs before exhausting
n
, return-1
.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N)
pernext(n)
call, whereN
is the number of runs in the encoding (worst case: we skip many runs). - 🧺 Space complexity:
O(M)
, whereM
is the length of the encoding array.