codekofi
← All problems

Problem 20

Medium40 XP

1 · Worked examples

0 / 4

Give it an input and say what you think comes back. It compiles and runs for real, so a wrong guess still shows you the answer — probe as much as you like. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 4 outputs correctly.

The accepted solution

1int countFrom(const string& s, int i, vector<int>& memo) {
2 int n = s.size();
3 if (i == n) return 1;
4 if (s[i] == '0') return 0;
5 if (memo[i] != -1) return memo[i];
6
7 int total = countFrom(s, i + 1, memo);
8 if (i + 1 < n) {
9 int two = (s[i] - '0') * 10 + (s[i + 1] - '0');
10 if (two <= 26) {
11 total += countFrom(s, i + 2, memo);
12 }
13 }
14 memo[i] = total;
15 return total;
16}
17
18int solution(const string& s) {
19 if (s.empty()) return 0;
20 vector<int> memo(s.size(), -1);
21 return countFrom(s, 0, memo);
22}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.