2
https://leetcode.com/problems/rle-iterator/4
next(): TC: O(n) in total over n calls5
Idea is to use two pointers are this.6
We maintain a ptr that points to the current element bucket. For a given n7
first iterate through the buckets which have freq < n, this means they won't8
have the last element. Once the iteration ends, either we will have no9
elements left or we will be on the bucket with freq >= n. Update the10
iteration ptr accordingly.14
// Tracks the even indices16
// Tracks the total length of array20
RLEIterator(vector<int> &encoding) {21
this->encoding = encoding;23
len = encoding.size();27
// Skip all the number buckets which will be completely exhausted28
// and we will still have some n left i.e n > 029
for (; curr < len && n > 0 && encoding[curr] < n; curr += 2) {30
// Skip the buckets with 0 frequency31
if (encoding[curr] == 0) continue;36
// If we still have elements left with non zero frequency then37
// the current bucket's frequency will be >= leftover n38
if (curr < len && encoding[curr] >= n) {39
// Exhaust the leftover n41
element = encoding[curr + 1];42
// If the bucket is completely exhausted, then move the iterator ptr to43
// next element for the next function call44
if (encoding[curr] == 0) curr += 2;51
* Your RLEIterator object will be instantiated and called as such:52
* RLEIterator* obj = new RLEIterator(encoding);53
* int param_1 = obj->next(n);