900. RLE Iterator
Explanation
To solve this problem, we can implement the RLEIterator class with two instance variables:
encoding
: to store the input run-length encoded array.index
: to keep track of the current position in the encoding array.
In the constructor, we initialize these variables. The next(n)
method iterates through the encoded array based on the value of n
. We exhaust the next n
elements by decrementing the count at the current index and moving to the next index if the count becomes zero. We return the value at the current index after each iteration.
class RLEIterator {
int[] encoding;
int index;
public RLEIterator(int[] encoded) {
encoding = encoded;
index = 0;
}
public int next(int n) {
while (index < encoding.length) {
if (n > encoding[index]) {
n -= encoding[index];
index += 2;
} else {
encoding[index] -= n;
return encoding[index + 1];
}
}
return -1;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.