RLE Iterator - Problem

We can use run-length encoding (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.

For example, the sequence arr = [8,8,8,5,5] can be encoded to be encoding = [3,8,2,5]. encoding = [3,8,0,9,2,5] and encoding = [2,8,1,8,2,5] are also valid RLE of arr.

Given a run-length encoded array, design an iterator that iterates through it.

Implement the RLEIterator class:

  • RLEIterator(int[] encoded) Initializes the object with the encoded array encoded.
  • int next(int n) Exhausts the next n elements and returns the last element exhausted in this way. If there is no element left to exhaust, return -1 instead.

Input & Output

Example 1 — Basic RLE Iterator
$ Input: encoded = [3,8,0,9,2,5], operations = [2,1,1,2]
Output: [8,8,5,-1]
💡 Note: RLE represents [8,8,8,5,5]. next(2) consumes 2 elements, returns 8. next(1) consumes 1 element, returns 8. next(1) consumes 1 element, returns 5. next(2) needs 2 elements but only 1 left, returns -1.
Example 2 — Empty Segments
$ Input: encoded = [1,2,0,3,4,1], operations = [1,1,1,1]
Output: [2,1,1,1]
💡 Note: RLE represents [2,1,1,1,1]. The 0-count segment is skipped. Each next(1) returns consecutive elements.
Example 3 — Exact Exhaustion
$ Input: encoded = [2,5], operations = [1,1,1]
Output: [5,5,-1]
💡 Note: RLE represents [5,5]. First two next(1) calls return 5, third call returns -1 as no elements left.

Constraints

  • 1 ≤ encoded.length ≤ 1000
  • encoded.length % 2 == 0
  • 1 ≤ encoded[i] ≤ 109
  • 1 ≤ n ≤ 109
  • At most 1000 calls will be made to next

Visualization

Tap to expand
RLE Iterator: Encoded [3,8,0,9,2,5] → Operations [2,1,1,2]380925RLE Encoded Array88855Decoded: [8,8,8,5,5]next(2)returns 8next(1)returns 8next(1)returns 5next(2)returns -1Result: [8,8,5,-1]
Understanding the Visualization
1
Input
RLE encoded array [3,8,0,9,2,5] represents sequence [8,8,8,5,5]
2
Process
Iterator tracks current segment and remaining count
3
Output
next() operations return last consumed element or -1
Key Takeaway
🎯 Key Insight: Track current RLE segment position and remaining count instead of expanding the entire array
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen