codekofi
← All problems

Problem 102

Medium

1 · Worked examples

0 / 3

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 3 outputs correctly.

The accepted solution

1struct Trie {
2 Trie* kids[26] = {};
3 bool word = false;
4};
5
6void insert(Trie* node, const string& text) {
7
8 for (char c : text) {
9
10 int i = c - 'a';
11
12 if (!node->kids[i]) {
13 node->kids[i] = new Trie();
14 }
15
16 node = node->kids[i];
17 }
18
19 node->word = true;
20}
21
22Trie* step(Trie* node, const string& text) {
23
24 for (char c : text) {
25
26 int i = c - 'a';
27
28 if (!node->kids[i]) {
29 return nullptr;
30 }
31
32 node = node->kids[i];
33 }
34
35 return node;
36}
37
38vector<string> solution(const vector<string>& ops,
39 const vector<string>& args) {
40
41 Trie root;
42 vector<string> ans;
43
44 int n = ops.size();
45
46 for (int i = 0; i < n; i++) {
47
48 if (ops[i] == "insert") {
49 insert(&root, args[i]);
50 ans.push_back("null");
51
52 } else if (ops[i] == "search") {
53
54 Trie* at = step(&root, args[i]);
55
56 if (at && at->word) {
57 ans.push_back("true");
58 } else {
59 ans.push_back("false");
60 }
61
62 } else {
63
64 Trie* at = step(&root, args[i]);
65
66 if (at) {
67 ans.push_back("true");
68 } else {
69 ans.push_back("false");
70 }
71 }
72 }
73
74 return ans;
75}

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.