27- Decoded String at Index
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
Initialize decodedLength
to 0: This variable will keep track of the total length of the decoded string as we iterate through it. It's initially set to 0.
Iterate through each character in the input string s
using a for-each loop:
If the character c
is a digit (checked using isdigit()
), it means we need to repeat the characters seen so far in the decoded string by a factor of c - '0'
times (convert the character to an integer). So, update decodedLength
by multiplying it by c - '0'
.
If the character is not a digit, it represents a single character in the decoded string, so increment decodedLength
by 1.
Reverse Iterate through the string s
from the end to the beginning (right to left):
For each character curr
at index i
:
If curr
is a digit, it means that the previous portion of the decoded string is repeated curr - '0'
times. To find the effective length of the decoded string up to this point, divide decodedLength
by curr - '0'
, and update decodedLength
accordingly.
Update k
by taking its modulo with the current decodedLength
. This ensures that k
stays within the bounds of the current portion of the decoded string.
If k
becomes 0 after the modulo operation or if decodedLength
equals k
, it means that k
corresponds to the current character curr
. In this case, return a string containing only curr
.
If the loop completes without finding a character to return, return an empty string, indicating that the decoded string is not found within the given input parameters.
Time Complexity: O(n)
Auxiliary Space Complexity: O(1)
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.