RLE Iterator - Problem
Run-Length Encoding (RLE) Iterator
Imagine you have a compressed sequence of numbers where instead of storing repeated values multiple times, you store pairs of
For example, the sequence
Your Mission: Design an iterator that can efficiently traverse through this compressed format without expanding the entire sequence into memory.
Key Operations:
โข
โข
Think of it like fast-forwarding through a compressed video - you need to jump ahead efficiently without decompressing everything!
Imagine you have a compressed sequence of numbers where instead of storing repeated values multiple times, you store pairs of
[count, value]. This is called Run-Length Encoding!For example, the sequence
[8,8,8,5,5] can be compressed to [3,8,2,5] meaning "3 times the number 8, then 2 times the number 5".Your Mission: Design an iterator that can efficiently traverse through this compressed format without expanding the entire sequence into memory.
Key Operations:
โข
RLEIterator(encoded) - Initialize with a run-length encoded arrayโข
next(n) - Skip the next n elements and return the last element consumed. If there aren't enough elements, return -1Think of it like fast-forwarding through a compressed video - you need to jump ahead efficiently without decompressing everything!
Input & Output
example_1.py โ Basic Usage
$
Input:
RLEIterator([3,8,0,9,2,5])
next(2), next(1), next(1), next(2)
โบ
Output:
8, 8, 5, -1
๐ก Note:
The sequence is [8,8,8,5,5]. next(2) consumes first 2 elements, returns 8. next(1) consumes 1 more (the last 8), returns 8. next(1) consumes first 5, returns 5. next(2) tries to consume 2 more but only 1 element left, returns -1.
example_2.py โ Zero Counts
$
Input:
RLEIterator([2,3,0,5,1,7])
next(1), next(2)
โบ
Output:
3, 7
๐ก Note:
Sequence is [3,3,7]. The (0,5) pair contributes no elements. next(1) returns 3, next(2) consumes the remaining 3 and the 7, returning 7.
example_3.py โ Large Skip
$
Input:
RLEIterator([1000000,1,1,2])
next(999999), next(2)
โบ
Output:
1, 2
๐ก Note:
First pair has 1 million 1's. next(999999) consumes 999,999 ones, returns 1. next(2) consumes the last 1 and the single 2, returns 2.
Constraints
- 1 โค encoding.length โค 1000
- encoding.length is even
- 0 โค encoding[i] โค 109
- 1 โค n โค 109
- At most 1000 calls will be made to next
Visualization
Tap to expand
Understanding the Visualization
1
Compressed Storage
Store data as [count, value] pairs like video frames with durations
2
Position Tracking
Maintain pointers to current segment and consumption within that segment
3
Efficient Skipping
Jump through segments consuming elements until request is satisfied
Key Takeaway
๐ฏ Key Insight: Instead of expanding compressed data, maintain smart pointers to navigate efficiently through the original compressed format, preserving both memory and the benefits of compression.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code