codekofi
← All problems

Problem 18

Medium40 XP

1 · Worked examples

0 / 3

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

The accepted solution

1void build(const string& digits, int i, string& current,
2 vector<string>& out) {
3 string keys[10] = {"", "", "abc", "def", "ghi",
4 "jkl", "mno", "pqrs", "tuv", "wxyz"};
5 int n = digits.size();
6 if (i == n) {
7 out.push_back(current);
8 return;
9 }
10
11 for (char ch : keys[digits[i] - '0']) {
12 current.push_back(ch);
13 build(digits, i + 1, current, out);
14 current.pop_back();
15 }
16}
17
18vector<string> solution(const string& digits) {
19 vector<string> out;
20 if (digits.empty()) return out;
21 string current;
22 build(digits, 0, current, out);
23 return out;
24}

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.