# RLE Iterator in C++

Suppose we have to create an iterator that iterates through a run-length encoded sequence. Here the iterator is initialized by calling RLEIterator(int[] A), where A is a run-length encoding of a sequence. So we can say that for all even i, A[i] tells us the number of times that the non-negative integer value A[i+1] is repeated in the sequence. Here iterator supports one function −

• next(int n): This function exhausts the next n elements (n >= 1) and returns the last element exhausted in this way. So if there is no element left to exhaust, next returns -1 instead.

Suppose we start with A = [3,8,0,9,2,5], which is a run-length encoding of the sequence [8,8,8,5,5]. This is done as the sequence can be read as "three eights, zero nines, two fives". So after initializing them with A, if we call next(2), next(1), next(1), next(2), then the final result will be [8, 8, 5, -1].

To solve this, we will follow these steps −

• In the initializer, initialize the array as A, and set index := 0

• In the next() method it takes n as input. this will work as follows

• while index < size of A and n > A[index]

• n := n – A[index], and increase index by 2

• if index > size of array A, then return -1

• A[index] := A[index] – n

• return A[index + 1]

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class RLEIterator {
public:
vector <int> A;
int idx = 0;
RLEIterator(vector<int>& A) {
this->A = A;
idx = 0;
}
int next(int n) {
while(idx < A.size() && n > A[idx]){
n -= A[idx];
idx += 2;
}
if(idx >= A.size()) return -1;
A[idx] = A[idx] - n;
return A[idx + 1];
}
};
main(){
vector<int> v = {3,8,0,9,2,5};
RLEIterator ob(v);
cout << (ob.next(2)) << endl;
cout << (ob.next(1)) << endl;
cout << (ob.next(1)) << endl;
cout << (ob.next(2)) << endl;
}

### Input

Initialize with [3,8,0,9,2,5] and call next(2), next(1), next(1), next(2)

## Output

8
8
5
-1