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
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
Then iterate backwards
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
Then, if k is 0 and the current character is a letter, return the letter because the solution has been found
Otherwise, reduce the size of the string. If the current character is a digit, divide the total size by the amount
Else, it's just another letter so decrement the size by 1
Tricky problem, thank you to the Editorial
Comments
Post a Comment