0
$\begingroup$

I can't find a concise algorithm for the following coding problem:

Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.You can assume that the messages are decodable. For example, '001' is not allowed.

I've recognized that any number <=26 can be represented 2 ways. I've tried to observe what happens when I add a number like 2, which can later form another 2-digit number with the one after it (e.g. 22 - 2 combinations, 222 - 3, 2222 - 5, 22222 - 8). But I can't seem to find a robust pattern.

This was a coding interview question that was supposed to last 30min, so I'm embarrassed I can't see the latent rule.

$\endgroup$

1 Answer 1

1
$\begingroup$

I believe the pattern you are looking for is dynamic programming. In the case at hand, the answer for a message can be based on answers for prefixes of the message. This leads to a linear time and linear space algorithm that computes answers for all prefixes in order of increasing length.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.