KatInterview

936. RLE Iterator

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to implement an iterator for a sequence that is encoded using Run-Length Encoding (RLE). The encoding array is a list of pairs [count, value], representing count repetitions of value. A naive solution of decompressing the entire sequence into an array would fail due to memory constraints, as the counts can be very large (up to 10^9).

Solution

RLE Iterator in Python

class RLEIterator:

    def __init__(self, encoding: List[int]):
        # Store a reference to the encoding list.
        self.encoding = encoding
        # Initialize a pointer to the start of the encoding.
        self.ptr = 0

    def next(self, n: int) -> int:
        # Iterate through the encoding as long as there are elements to consume.
        while self.ptr < len(self.encoding):
            # If the current block has enough elements to satisfy the request.
            if self.encoding[self.ptr] >= n:
                # Decrease the count of the current element.
                self.encoding[self.ptr] -= n
                # Return the value of the current element.
                return self.encoding[self.ptr + 1]
            else:
                # The current block does not have enough elements. Exhaust it.
                # Decrease n by the number of elements in the current block.
                n -= self.encoding[self.ptr]
                # Move the pointer to the next block (count and value).
                self.ptr += 2
        
        # If the loop finishes, it means we have exhausted all elements
        # but couldn't satisfy the request for n elements.
        return -1


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

RLE Iterator in Java

class RLEIterator {
    private int[] encoding;
    private int ptr;

    public RLEIterator(int[] encoding) {
        // Store a reference to the encoding array.
        this.encoding = encoding;
        // Initialize a pointer to the start of the encoding.
        this.ptr = 0;
    }
    
    public int next(int n) {
        // Iterate through the encoding as long as there are elements to consume.
        while (ptr < encoding.length) {
            // If the current block has enough elements to satisfy the request.
            if (encoding[ptr] >= n) {
                // Decrease the count of the current element.
                encoding[ptr] -= n;
                // Return the value of the current element.
                return encoding[ptr + 1];
            } else {
                // The current block does not have enough elements. Exhaust it.
                // Decrease n by the number of elements in the current block.
                n -= encoding[ptr];
                // Move the pointer to the next block (count and value).
                ptr += 2;
            }
        }
        // If the loop finishes, it means we have exhausted all elements
        // but couldn't satisfy the request for n elements.
        return -1;
    }
}

/**
 * Your RLEIterator object will be instantiated and called as such:
 * RLEIterator obj = new RLEIterator(encoding);
 * int param_1 = obj.next(n);
 */

RLE Iterator in C++

class RLEIterator {
private:
    vector<int> encoding;
    int ptr;

public:
    RLEIterator(vector<int>& encoding) {
        // Make a copy of the encoding vector to store the state.
        this->encoding = encoding;
        // Initialize a pointer to the start of the encoding.
        this->ptr = 0;
    }
    
    int next(int n) {
        // Iterate through the encoding as long as there are elements to consume.
        while (ptr < encoding.size()) {
            // If the current block has enough elements to satisfy the request.
            if (encoding[ptr] >= n) {
                // Decrease the count of the current element.
                encoding[ptr] -= n;
                // Return the value of the current element.
                return encoding[ptr + 1];
            } else {
                // The current block does not have enough elements. Exhaust it.
                // Decrease n by the number of elements in the current block.
                n -= encoding[ptr];
                // Move the pointer to the next block (count and value).
                ptr += 2;
            }
        }
        // If the loop finishes, it means we have exhausted all elements
        // but couldn't satisfy the request for n elements.
        return -1;
    }
};

/**
 * Your RLEIterator object will be instantiated and called as such:
 * RLEIterator* obj = new RLEIterator(encoding);
 * int param_1 = obj->next(n);
 */

RLE Iterator in TypeScript

class RLEIterator {
    private encoding: number[];
    private ptr: number;

    constructor(encoding: number[]) {
        // Store a reference to the encoding array.
        this.encoding = encoding;
        // Initialize a pointer to the start of the encoding.
        this.ptr = 0;
    }

    next(n: number): number {
        // Iterate through the encoding as long as there are elements to consume.
        while (this.ptr < this.encoding.length) {
            // If the current block has enough elements to satisfy the request.
            if (this.encoding[this.ptr] >= n) {
                // Decrease the count of the current element.
                this.encoding[this.ptr] -= n;
                // Return the value of the current element.
                return this.encoding[this.ptr + 1];
            } else {
                // The current block does not have enough elements. Exhaust it.
                // Decrease n by the number of elements in the current block.
                n -= this.encoding[this.ptr];
                // Move the pointer to the next block (count and value).
                this.ptr += 2;
            }
        }
        // If the loop finishes, it means we have exhausted all elements
        // but couldn't satisfy the request for n elements.
        return -1;
    }
}

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

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.