RLE Iterator — LeetCode 900 Python Solution

MediumDesignArrayCountingIterator
Problem
#900
Pattern
Hash Map
Reading time
4 min

The 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.

Example

Input
["RLEIterator", "next", "next", "next", "next"]
Output
[null, 8, 8, 5, -1]
Explanation
RLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5].

Python solution

Python
class RLEIterator:
    def __init__(self, encoding: List[int]):
        self.encoding = encoding
        self.i = 0
        self.j = 0

    def next(self, n: int) -> int:
        while self.i < len(self.encoding):
            if self.encoding[self.i] - self.j < n:
                n -= self.encoding[self.i] - self.j
                self.i += 2
                self.j = 0
            else:
                self.j += n
                return self.encoding[self.i + 1]
        return -1


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

Complexity

MeasureComplexity
TimeO(n + q)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 900. RLE Iterator is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 900. RLE Iterator?
LeetCode 900. RLE Iterator is rated Medium on LeetCode.
What is the time complexity of LeetCode 900. RLE Iterator?
The Python solution on this page runs in O(n + q).
What is the space complexity of LeetCode 900. RLE Iterator?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 900. RLE Iterator cover?
LeetCode 900. RLE Iterator is tagged Design, Array, Counting and Iterator on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview