codekofi
← All problems

Problem 20

Medium

1 · Worked examples

0 / 4

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. 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
3 int n = s.size();
4
5 if (i == n) {
6 return 1;
7 }
8
9 if (s[i] == '0') {
10 return 0;
11 }
12
13 if (memo[i] != -1) {
14 return memo[i];
15 }
16
17 int total = countFrom(s, i + 1, memo);
18
19 if (i + 1 < n) {
20
21 int two = (s[i] - '0') * 10 + (s[i + 1] - '0');
22
23 if (two <= 26) {
24 total += countFrom(s, i + 2, memo);
25 }
26 }
27
28 memo[i] = total;
29 return total;
30}
31
32int solution(const string& s) {
33
34 if (s.empty()) {
35 return 0;
36 }
37
38 vector<int> memo(s.size(), -1);
39
40 return countFrom(s, 0, memo);
41}

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.