1199. Kth Letter of the Runs

Medium3.5 points estimatedBinary SearchPrefix SumString

A log archive stores text in run-length form, such as a3b12c1: each letter is followed by how many times it repeats. Given encoded and a list of 1-based positions queries, find the letter at each position of the expanded text without expanding it, which could hold trillions of characters.

Return the answers joined into one string in query order. A position beyond the end of the expanded text answers '#'. Neighbouring runs may use the same letter, and a query may repeat.

Build prefix sums of the run lengths once, then binary search each query, for O((r + q) log r) time and O(r) space with r runs and q queries. Totals reach about 10^13, so use 64-bit integers.

Example 1

Input:
encoded = "a3b2", queries = [1,3,4,5,6]
Output:
"aabb#"
Explanation:

Positions 1 to 3 are a, positions 4 and 5 are b, and position 6 is past the end.

Example 2

Input:
encoded = "z1", queries = [1]
Output:
"z"
Explanation:

A single run of one z.

Example 3

Input:
encoded = "x1000000000y1000000000"queries = [1000000000,1000000001,2000000000,2000000001,1000000000000000]
Output:
"xyy##"
Explanation:

The run boundary is at 10^9, and 2*10^9 is the last valid position.

Constraints

1 ≤ runs ≤ 104, each count in [1, 109]

1 ≤ queries.length ≤ 104

1 ≤ queries[i] ≤ 1015

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O((r+q) log r)
Space
O(r)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…