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.


1 Answer 1


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.


Your Answer

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

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