codekofi
← All problems

Problem 15

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

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

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.