Wednesday, September 27th

 Tape compression

Following a compression scheme for a string, where a letter is added to the string and a number signifies copies of the entire string, return the kth letter of the decoded string

Brute force is a straight forward approach, but times out for larger encodings

A key observation for an efficient solution is that for a string of length n multiplied any number of times, and an index k, the output letter will be the same as k%n 

With this in mind, we can work backwards to find the answer

To work backwards, we first find the size of the string at the end of the problem.  Iterate over the input string, if a character is a letter increase the size by 1, otherwise if it's a digit, multiply the length by the digit amount

string decodeAtIndex(string S, int K) {
        long totalsize = 0;
int n = s.size();

for (int i = 0; i < n; ++i) {
if (isdigit(s[i]))
totalsize *= s[i] - '0';
else
totalsize++;
}

        ...
    }

Then iterate backwards

for (int i = N-1; i >=0; --i) {
        ...
    }

at each iteration, recalculate K by modding it with the size of the string.  At the beginning it won't make a difference, but after the string is divided it will

k %= totalsize;

Then, if k is 0 and the current character is a letter, return the letter because the solution has been found

if (k == 0 && isalpha(s[i]))
return (string)s[i];

Otherwise, reduce the size of the string.  If the current character is a digit, divide the total size by the amount

    if (isdigit(s[i]))
totalsize /= s[i] - '0';

Else, it's just another letter so decrement the size by 1

    else
totalsize--;

Tricky problem, thank you to the Editorial 


Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th