**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 :

` ````
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

## Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →## Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →## Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →## Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →## Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →## Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →