Skip to content

Commit d3f1d89

Browse files
committed
Add solution #900
1 parent f95688d commit d3f1d89

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -710,6 +710,7 @@
710710
897|[Increasing Order Search Tree](./0897-increasing-order-search-tree.js)|Easy|
711711
898|[Bitwise ORs of Subarrays](./0898-bitwise-ors-of-subarrays.js)|Medium|
712712
899|[Orderly Queue](./0899-orderly-queue.js)|Hard|
713+
900|[RLE Iterator](./0900-rle-iterator.js)|Medium|
713714
901|[Online Stock Span](./0901-online-stock-span.js)|Medium|
714715
905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy|
715716
909|[Snakes and Ladders](./0909-snakes-and-ladders.js)|Medium|

solutions/0900-rle-iterator.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* 900. RLE Iterator
3+
* https://leetcode.com/problems/rle-iterator/
4+
* Difficulty: Medium
5+
*
6+
* We can use run-length encoding (i.e., RLE) to encode a sequence of integers. In a run-length
7+
* encoded array of even length encoding (0-indexed), for all even i, encoding[i] tells us the
8+
* number of times that the non-negative integer value encoding[i + 1] is repeated in the sequence.
9+
* - For example, the sequence arr = [8,8,8,5,5] can be encoded to be encoding = [3,8,2,5].
10+
* encoding = [3,8,0,9,2,5] and encoding = [2,8,1,8,2,5] are also valid RLE of arr.
11+
*
12+
* Given a run-length encoded array, design an iterator that iterates through it.
13+
*
14+
* Implement the RLEIterator class:
15+
* - RLEIterator(int[] encoded) Initializes the object with the encoded array encoded.
16+
* - int next(int n) Exhausts the next n elements and returns the last element exhausted in this
17+
* way. If there is no element left to exhaust, return -1 instead.
18+
*/
19+
20+
/**
21+
* @param {number[]} encoding
22+
*/
23+
var RLEIterator = function(encoding) {
24+
this.pairs = [];
25+
this.index = 0;
26+
this.count = 0;
27+
28+
for (let i = 0; i < encoding.length; i += 2) {
29+
if (encoding[i] > 0) {
30+
this.pairs.push([encoding[i], encoding[i + 1]]);
31+
}
32+
}
33+
};
34+
35+
/**
36+
* @param {number} n
37+
* @return {number}
38+
*/
39+
RLEIterator.prototype.next = function(n) {
40+
while (n > 0 && this.index < this.pairs.length) {
41+
const available = this.pairs[this.index][0] - this.count;
42+
43+
if (n <= available) {
44+
this.count += n;
45+
return this.pairs[this.index][1];
46+
}
47+
48+
n -= available;
49+
this.count = 0;
50+
this.index++;
51+
}
52+
53+
return -1;
54+
};

0 commit comments

Comments
 (0)