![]() |
VOOZH | about |
Given a compressed string composed of lowercase characters and numbers, the task is to decode the compressed string and to find out the character located at the Kth position in the uncompressed string, You can transform the string by following the rule that when you encounter a numeric value "n", repeat the preceding substring starting from index 0 'n' times
Examples:
Input: S = "ab2c3" K = 10
Output: "c"
Explanation:
- When traversing the string we got the first numeric value 2,
- here the preceding Substring =" ab "
- So "ab" is repeated twice, Now the string Will be "ababc3".
- The second numeric value we got is 3,
- Now, our preceding String is "ababc"
- So it will be repeated 3 times.
- Now the expanded string will be "ababc" + "ababc" + "ababc" = "ababcababcababc"
- 10th character is "c", so the output is "c".
Input: S = "z3a2s1" K = 12
Output: -1
Explanation: Expanded string will be "zzzazzzas" and have a length of 9, so output -1 (as the Kth index does not exist)
Naive Approach: The basic way to solve the problem is as follows:
The idea is to generate the expanded string and then find the Kth value of that string. To do so we will use a string "decoded" and insert the compressed string when encounter a string and if we encounter a digit then we will multiply the string the digit times and store it in "decoded" string .
Below is the implementation of the above idea:
c
Time Complexity: O(N),
Auxiliary Space: O(N), where N is the length of the expanded string.
Efficient Approach: To solve the problem without expanding the string using Recursion :
Below is the implementation of the above idea:
c
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1).