Problem Description
Design an iterator for a run-length encoded array. The iterator is initialized with an encoded array where for every even index i, the value at encoding[i] represents the count of the integer given at encoding[i+1]. The iterator has a method next(n) that exhausts the next n elements in the sequence. It returns the last element that was exhausted if possible, or -1 if there aren’t enough elements.
Key Insights
- Maintain an index pointer into the encoded array to avoid decompressing the entire array.
- In each call to next(n), decrement the count at the current pointer.
- If the current count is not enough to cover n, subtract the count from n and move to the next pair.
- Return the corresponding integer when the current count is sufficient; if the pointer goes out of range, return -1.
Space and Time Complexity
Time Complexity: O(1) on average per next call, though in worst-case each call may iterate over multiple encoding pairs (O(m) where m is number of encoding pairs, but m <= 500 given constraints). Space Complexity: O(1) as only a few extra variables are used.
Solution
We implement the RLEIterator by storing the encoded sequence and a pointer which tracks the current position. For each call to next(n), we subtract from the current count until either we have used up n or exhausted all pairs. If the count at the current position is sufficient, we return the corresponding integer after deducting n from the count. Otherwise, we decrement n by the current count and advance the pointer to the next encoding pair. The trick is to work directly with the encoding array without fully expanding it into its original sequence.