27- Decoded String at Index
The problem can be found at the following link: Question Link
My Approach
Initialize
decodedLengthto 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
susing a for-each loop:If the character
cis 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, updatedecodedLengthby multiplying it byc - '0'.If the character is not a digit, it represents a single character in the decoded string, so increment
decodedLengthby 1.
Reverse Iterate through the string
sfrom the end to the beginning (right to left):For each character
currat indexi:If
curris 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, dividedecodedLengthbycurr - '0', and updatedecodedLengthaccordingly.Update
kby taking its modulo with the currentdecodedLength. This ensures thatkstays within the bounds of the current portion of the decoded string.If
kbecomes 0 after the modulo operation or ifdecodedLengthequalsk, it means thatkcorresponds 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++)
class Solution {
public:
string decodeAtIndex(string s, int k) {
long long decodedLength = 0;
for(auto c : s){
if(isdigit(c)){
decodedLength = decodedLength * ( c - '0');
}else{
decodedLength++;
}
}
for(int i = s.length() - 1; i >= 0; i--){
char curr = s[i];
if(isdigit(curr)){
decodedLength = decodedLength/(curr - '0');
k = k % decodedLength;
}else{
if( k == 0 || decodedLength == k){
return string(1,curr);
}
decodedLength--;
}
}
return "";
}
};
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
Was this helpful?