Leetcode 900: RLE Iterator

grid47
grid47
Exploring patterns and algorithms
Aug 9, 2024 7 min read

We are given a run-length encoded array where every even-indexed element specifies how many times the following odd-indexed element (a number) is repeated in the original sequence. Your task is to implement an iterator that can return the next ’n’ elements from the decoded sequence when requested.
Problem
Approach
Steps
Complexity
Input: You are given a run-length encoded array where encoding[i] gives the frequency of encoding[i+1] in the sequence. You need to create an iterator that can return the next 'n' elements when requested.
Example: Input: ['RLEIterator', 'next', 'next', 'next', 'next'] [[[2, 10, 1, 20, 3, 5]], [1], [2], [3], [4]]
Constraints:
• 2 <= encoding.length <= 1000
• encoding.length is even.
• 0 <= encoding[i] <= 10^9
• 1 <= n <= 10^9
• At most 1000 calls will be made to next.
Output: The output is the value of the last element returned after exhausting the next 'n' elements from the sequence, or -1 if there are no more elements to exhaust.
Example: Output: [null, 20, 20, 5, -1]
Constraints:
• The result for each next(n) call will be an integer or -1 if there are no more elements.
Goal: To create an iterator that processes run-length encoded data and efficiently returns the next 'n' elements in sequence.
Steps:
• 1. Use an index to traverse the run-length encoded array.
• 2. For each next(n) call, decrement the count of the remaining elements in the current sequence while keeping track of the last number encountered.
• 3. Once the count of a sequence is exhausted, move to the next run-length encoded pair and continue.
• 4. If no more elements are available, return -1.
Goal: The solution should efficiently process the next() calls and ensure that it handles large sequences correctly.
Steps:
• At most 1000 calls will be made to next.
• The input encoding array is guaranteed to have an even length.
Assumptions:
• The input encoding array will always have an even length.
• Each encoding pair will be a valid representation of a sequence of numbers.
• The solution should efficiently handle repeated calls to the 'next' method.
Input: Input: ['RLEIterator', 'next', 'next', 'next', 'next'] [[[2, 10, 1, 20, 3, 5]], [1], [2], [3], [4]]
Explanation: The run-length encoded array [2, 10, 1, 20, 3, 5] represents the sequence [10, 10, 20, 5, 5, 5]. Calling next(1) returns 20, next(2) returns 20 again, next(3) returns 5, and next(4) returns -1 as the sequence is exhausted.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus