1217. Deep Unpack Lookup
A compressed log stores repeated text as a count followed by a bracketed group, so 2[ab3[c]]x stands for abcccabcccx. The string encoded contains lowercase letters, positive counts written in decimal, and square brackets. A count is always immediately followed by [ and a non-empty group, groups may be nested, and plain letters may appear inside or outside groups.
The decoded text can be astronomically long, so do not build it. Given the 1-based position k, return the character at position k of the decoded text, or '#' if k is larger than the decoded length. Compute each group's length with a cap so it never overflows, then descend through the groups, reducing k modulo the length of the repeated block at each level. Aim for time proportional to the length of encoded times the nesting depth.
Example 1
- Input:
- encoded = "2[ab3[c]]x", k = 4
- Output:
- "c"
- Explanation:
The decoded text is
abcccabcccx, whose 4th character isc.
Example 2
- Input:
- encoded = "2[ab3[c]]x", k = 11
- Output:
- "x"
- Explanation:
The last character of the 11-character decoded text is
x.
Example 3
- Input:
- encoded = "2[ab3[c]]x", k = 12
- Output:
- "#"
- Explanation:
The decoded text has only 11 characters, so position 12 gives
#.
Constraints
1 ≤ encoded.length ≤ 104
1 ≤ k ≤ 1015
1 ≤ count ≤ 109, nesting depth at most 100, input well-formed
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 * depth)
- Space
- O(n)