2026-01-01 13:05:15 +0300 MSK

RLE Iterator

Code

class RLEIterator:

    def __init__(self, encoding: List[int]):
        self.enc = encoding
        self.enc.reverse()

    def next(self, n: int) -> int:
        while self.enc and n > 0:
            count = self.enc[-1]
            if count == 0:
                self.enc.pop()
                self.enc.pop()
            elif count >= n:
                self.enc[-1] -= n
                return self.enc[-2]
            else:
                n -= count
                self.enc.pop()
                self.enc.pop()
        return -1

# Your RLEIterator object will be instantiated and called as such:
# obj = RLEIterator(encoding)
# param_1 = obj.next(n)