Problem statement

https://binarysearch.com/problems/Run-Length-Decoded-String-Iterator/

Solution

Variation of Leetcode 0604 Design Compressed String Iterator, here I use solution with groupby.

Complexity

It is O(1) for time and O(m) for space to keep our compressed string.

Code

class RunLengthDecodedIterator:
    def __init__(self, s):
        B = ["".join(x) for _, x in groupby(s, key=lambda x: x.isdigit())]
        self.pairs = [[B[2*i+1], int(B[2*i])] for i in range(len(B)//2)][::-1]

    def next(self):
        ans = self.pairs[-1][0]
        self.pairs[-1][1] -= 1
        if self.pairs[-1][1] == 0: self.pairs.pop()
        return ans

    def hasnext(self):
        return len(self.pairs) != 0