#900

RLE Iterator

Medium
ArrayDesignCountingIteratorArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution maintains the current position in the encoded array and keeps track of how many elements are left to consume. This avoids reconstructing the entire sequence and allows for efficient element retrieval.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize the iterator with the encoded array, setting the current index and counts.
  2. 2Step 2: In the 'next(n)' method, check if there are enough elements left to exhaust.
  3. 3Step 3: If there are enough elements, decrement the count and return the current value; otherwise, return -1.
solution.py21 lines
1class RLEIterator:
2    def __init__(self, encoded):
3        self.encoded = encoded
4        self.index = 0
5        self.current_count = 0
6        self.current_value = 0
7
8    def next(self, n):
9        while n > 0:
10            if self.current_count == 0:
11                if self.index >= len(self.encoded):
12                    return -1
13                self.current_count = self.encoded[self.index]
14                self.current_value = self.encoded[self.index + 1]
15                self.index += 2
16            if n <= self.current_count:
17                self.current_count -= n
18                return self.current_value
19            n -= self.current_count
20            self.current_count = 0
21        return -1

Complexity note: This complexity is linear because we only traverse the encoded array once, and we keep track of our position without needing to reconstruct the entire sequence.

  • 1Understanding run-length encoding is crucial for this problem.
  • 2Efficiently managing state (current index and counts) is key to optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.