27- Decoded String at Index
The problem can be found at the following link: Question Link
My Approach
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 usingisdigit()
), it means we need to repeat the characters seen so far in the decoded string by a factor ofc - '0'
times (convert the character to an integer). So, updatedecodedLength
by multiplying it byc - '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 indexi
:If
curr
is a digit, it means that the previous portion of the decoded string is repeatedcurr - '0'
times. To find the effective length of the decoded string up to this point, dividedecodedLength
bycurr - '0'
, and updatedecodedLength
accordingly.Update
k
by taking its modulo with the currentdecodedLength
. This ensures thatk
stays within the bounds of the current portion of the decoded string.If
k
becomes 0 after the modulo operation or ifdecodedLength
equalsk
, it means thatk
corresponds to the current charactercurr
. In this case, return a string containing onlycurr
.
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 and Auxiliary Space Complexity
Time Complexity:
O(n)
Auxiliary Space Complexity:
O(1)
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. 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 rishabhv12/Daily-Leetcode-Solution repository.
Last updated