codekofi
← All problems

Problem 15

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

1bool solveFrom(const string& s, int i,
2 const unordered_set<string>& words,
3 vector<int>& memo) {
4
5 int n = s.size();
6
7 if (i == n) {
8 return true;
9 }
10
11 if (memo[i] != -1) {
12 return memo[i] == 1;
13 }
14
15 for (int j = i + 1; j <= n; j++) {
16
17 string piece = s.substr(i, j - i);
18
19 if (words.count(piece) && solveFrom(s, j, words, memo)) {
20 memo[i] = 1;
21 return true;
22 }
23 }
24
25 memo[i] = 0;
26 return false;
27}
28
29bool solution(const string& s, const vector<string>& words) {
30
31 unordered_set<string> lookup(words.begin(), words.end());
32 vector<int> memo(s.size(), -1);
33
34 return solveFrom(s, 0, lookup, memo);
35}

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.