Similar Problems

Similar Problems not available

Rle Iterator - Leetcode Solution

Companies:

  • google

LeetCode:  Rle Iterator Leetcode Solution

Difficulty: Medium

Topics: design array  

Problem Statement: Implement the run-length encoding iterator.

You are given an iterator that combinations of characters and integers of a string. For example, [a, 1, b, 2, c, 3] signifies that there is 1 'a', 2 'b', and 3 'c'.

Your job is to implement the RunLengthEncodingIterator class, which implements the Iterator interface. It should support hasNext(), which returns whether there is still a next element, and next(), which returns the next element as an array [char, value].

If the current element is 'a' and the next element is 'a', you should combine them into [a, 2]. Constraints:

  • 1 <= encoding.length <= 105
  • encoding[i][0] is a lowercase English letter.
  • encoding[i][1] is an integer in the range [1, 100].

Solution:

The problem can be solved using a queue data structure and a pointer. We can push each character from the given input encoding in the queue with its occurrence, i.e., input encoding [a, 2, b, 3, c, 4] will be pushed to the queue as (a,2), (b,3), (c,4). Initially, we place our pointer at the starting of the queue. When hasNext() method is called, we return whether the queue is not empty. If the queue is not empty, we return true, else false. When next() method is called, we return the front of the queue in the form of an array [char, value] and push the character back to the queue, reducing its occurrence.

To handle the merging of characters, we can maintain a separate variable lastChar. If the front character of the queue and lastChar are the same, we add its occurrence to lastChar occurrence and pop the front element of the queue. else, we update the lastChar variable with the front character of the queue.

Code:

class RunLengthEncodingIterator implements Iterator<char[]> {

private Queue<Pair<Character, Integer>> q;
private Pair<Character, Integer> lastChar;

public RunLengthEncodingIterator(String s) {
    q = new LinkedList<>();
    lastChar = null;
    for(int i=0; i<s.length(); i+=2) {
        q.add(new Pair(s.charAt(i), s.charAt(i+1)-'0'));
    }
}

public boolean hasNext() {
    if(!q.isEmpty()) 
        return true;
    else 
        return false;
}

public char[] next() {
    if(!hasNext()) 
        return new char[]{'#', -1};
    
    Pair<Character, Integer> pair = q.poll();
    char ch = pair.getKey();
    int val = pair.getValue();
    
    if(lastChar != null && lastChar.getKey() == ch) {
        lastChar = new Pair(ch, lastChar.getValue()+val);
    } else {
        lastChar = new Pair(ch, val);
    }
    q.add(lastChar);
    return new char[]{lastChar.getKey(), lastChar.getValue()};
}

}

Time Complexity: O(n), where n is the length of the input string.

Space Complexity: O(n), where n is the length of the input string.

Rle Iterator Solution Code

1