From 55ffc32fed5cc8f2e25996c6e27b80b8fa7aaf22 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 6 Aug 2022 17:34:50 +0200 Subject: [PATCH] problems: add an RLE Iterator Signed-off-by: Matej Focko --- problems/rle-iterator.java | 55 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 problems/rle-iterator.java diff --git a/problems/rle-iterator.java b/problems/rle-iterator.java new file mode 100644 index 0000000..3103214 --- /dev/null +++ b/problems/rle-iterator.java @@ -0,0 +1,55 @@ +class RLEIterator { + private int[] encoding; + private int major = 0; + private int minor = 0; + + public RLEIterator(int[] encoding) { + this.encoding = encoding; + } + + private void nextSegment() { + major += 2; + minor = 0; + } + + private int lastConsumed() { + if (major == 0 && minor == 0) { + // Haven't consumed anything + return -1; + } else if (major <= encoding.length && minor == 0) { + // Consumed last element of a previous segment + return encoding[major - 1]; + } else if (major >= encoding.length) { + // Everything was consumed + return -1; + } + + // Last consumed from the current segment + return encoding[major + 1]; + } + + public int next(int n) { + while (n > 0 && major < encoding.length) { + int consumed = Math.min(n, encoding[major] - minor); + + n -= consumed; + minor += consumed; + + if (minor == encoding[major]) { + nextSegment(); + } + } + + if (n > 0) { + return -1; + } + + return lastConsumed(); + } +} + +/** + * Your RLEIterator object will be instantiated and called as such: + * RLEIterator obj = new RLEIterator(encoding); + * int param_1 = obj.next(n); + */