1710. Peek Into the Unpacked
A compressed message s is built from lowercase letters and groups written k[...], meaning that the text inside the brackets is repeated k times; groups may be nested. For example "ab3[c2[d]]e" unpacks to "abcddcddcdde". The unpacked text can be astronomically long, up to 10^15 characters, so it must never be built.
Given s and a 0-based position idx, return the character at that position of the unpacked text. First compute the unpacked length of every group with a stack. Then scan s: skip whole groups whose unpacked length is at most idx (subtracting it), and when idx falls inside a group, replace idx by idx modulo the length of one copy of the group's contents and descend into it. Every group contains at least one letter, k is written in decimal digits, and idx is always valid. Target O(n) time and O(n) space.
Example 1
- Input:
- s = "ab3[c2[d]]e", idx = 5
- Output:
- "c"
- Explanation:
The text is abcddcddcdde and position 5 holds the second 'c'.
Example 2
- Input:
- s = "a", idx = 0
- Output:
- "a"
- Explanation:
The text is just "a" and position 0 is 'a'.
Example 3
- Input:
- s = "2[xy]z", idx = 4
- Output:
- "z"
- Explanation:
"2[xy]z" unpacks to xyxyz and position 4 is the final 'z'.
Constraints
1 ≤ s.length ≤ 2000
1 ≤ k ≤ 109
Every group is non-empty and brackets are balanced
Total unpacked length ≤ 1015
0 ≤ idx < unpacked length
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(n)
- Space
- O(n)