Lazy Run-Length Decoding - Google Top Interview Questions


Problem Statement :


Implement a data structure RunLengthDecoder which implements the following methods:

RunLengthDecoder(string s) which takes a string s that is run-length encoded.

string value(int i) which returns the character at index i of the run-length decoded version of s.

string valueInRange(string c, int i, int j) which returns the first lowercase alphabet character that is greater than or equal to c from the range [i, j) of the decoded string. 

You can assume that the range contains characters that are in ascending order. If no such character exists, return "?"
Constraints

n ≤ 100,000 where n is the length of s

k ≤ 100,000 where k is the number of calls to value and valueInRange

Example 1

Input

methods = ["constructor", "value", "value", "valueInRange", "valueInRange", "valueInRange"]

arguments = [["3a3b2c1d1a"], [0], [4], ["a", 0, 9], ["b", 3, 9], ["e", 3, 9]]`

Output

[None, "a", "b", "a", "b", "?"]
Explanation

r = RunLengthDecoder("3a3b2c1d1a") # In decoded version it's "aaabbbccda"

r.value(0) == "a"

r.value(4) == "b"

r.valueInRange("a", 0, 9) == "a"

r.valueInRange("b", 3, 9) == "b"

r.valueInRange("e", 3, 9) == "?"



Solution :



title-img




                        Solution in C++ :

class RunLengthDecoder {
    public:
    map<char, vector<pair<int, int>>> charToRanges;
    vector<pair<int, int>> ranges;
    vector<char> chars;
    RunLengthDecoder(string s) {
        int curr = 0;
        int amt = 0;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] >= 'a' && s[i] <= 'z') {
                charToRanges[s[i]].emplace_back(amt, amt + curr);
                ranges.emplace_back(amt, amt + curr);
                chars.push_back(s[i]);
                amt += curr;
                curr = 0;
            } else {
                curr *= 10;
                curr += s[i] - '0';
            }
        }
        assert(curr == 0);
    }

    string value(int i) {
        auto it = upper_bound(ranges.begin(), ranges.end(), make_pair(i + 1, (int)-1e9));
        it--;
        int idx = it - ranges.begin();
        return string(1, chars[idx]);
    }

    string valueInRange(string c, int i, int j) {
        for (char ch = c[0]; ch <= 'z'; ch++) {
            auto it = upper_bound(charToRanges[ch].begin(), charToRanges[ch].end(),
                                  make_pair(j, (int)-1e9));
            if (it != charToRanges[ch].begin()) it--;
            if (it == charToRanges[ch].end()) continue;
            pair<int, int> key = *it;
            if (key.second <= i || key.first >= j) continue;
            return string(1, ch);
        }
        return "?";
    }
};
                    


                        Solution in Java :

import java.util.*;

class RunLengthDecoder {
    private StringBuilder sb = new StringBuilder();
    private List<Integer> begins = new ArrayList<>();

    public RunLengthDecoder(String s) {
        for (int i = 0, end = 0; i != s.length(); i++) {
            int j = i;
            while (Character.isDigit(s.charAt(j + 1))) j++;
            begins.add(end);
            int len = Integer.parseInt(s.substring(i, j + 1));
            if (len != 0) {
                end += Integer.parseInt(s.substring(i, j + 1));
                sb.append(s.charAt(j + 1));
            }
            i = j + 1;
        }
    }

    public String value(int i) {
        int idx = Collections.binarySearch(begins, i);
        if (idx < 0)
            idx = -2 - idx;
        return sb.substring(idx, idx + 1);
    }

    public String valueInRange(String c, int i, int j) {
        int idx = Collections.binarySearch(begins, i);
        if (idx < 0)
            idx = -2 - idx;
        final char ch = c.charAt(0);
        for (int round = 0; idx != sb.length() && round != 26; round++, idx++) {
            if (begins.get(idx) >= j)
                break;
            if (sb.charAt(idx) >= ch)
                return Character.toString(sb.charAt(idx));
        }
        return "?";
    }
}
                    


                        Solution in Python : 
                            
class RunLengthDecoder:
    def __init__(self, s):
        self.chars = []
        self.indexes = [0]

        char_count = 0
        for char in s:
            if not char.isdigit():
                self.chars.append(char)
                self.indexes.append(self.indexes[-1] + char_count)
                char_count = 0
            else:
                char_count = char_count * 10 + int(char)

        self.next_indexes = [[self.indexes[-1]] * 26 for _ in range(len(s) + 1)]

        for i in range(len(self.chars) - 1, -1, -1):
            self.next_indexes[i] = self.next_indexes[i + 1][:]
            char_num = ord(self.chars[i]) - ord("a")
            self.next_indexes[i][char_num] = self.indexes[i]

    def value(self, i):
        char_index = max(0, bisect_right(self.indexes, i) - 1)
        return self.chars[char_index]

    def valueInRange(self, c, i, j):
        char_index = max(0, bisect_right(self.indexes, i) - 1)
        next_indexes = self.next_indexes[char_index]
        char_num = ord(c) - ord("a")
        for num in range(char_num, 26):
            if next_indexes[num] < j:
                return chr(num + ord("a"))
        return "?"
                    


View More Similar Problems

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →