Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# 17. Letter Combinations of a Phone Number

[LeetCode problem 17](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)

- **Difficulty**: Medium
- **Tags**: hash-table, string, backtracking

## Description

Given a string of digits from `2` to `9`, return all possible letter
combinations the digits could represent on a phone keypad, in any order.
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include "solution.hpp"

#include <unordered_map>

namespace leetcode::p0017 {

std::vector<std::string> solve(const std::string& digits) {
if (digits.empty()) {
return {};
}

static const std::unordered_map<char, std::string> keypad{
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"},
};

std::vector<std::string> result{""};

for (char digit : digits) {
std::vector<std::string> next;
for (const auto& combination : result) {
for (char letter : keypad.at(digit)) {
next.push_back(combination + letter);
}
}
result = std::move(next);
}

return result;
}

} // namespace leetcode::p0017
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#pragma once

#include <string>
#include <vector>

namespace leetcode::p0017 {

// optimized: O(4^n * n) time (n = digits.size()), O(4^n * n) space — build
// the combinations iteratively, one digit at a time.
std::vector<std::string> solve(const std::string& digits);

} // namespace leetcode::p0017
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#include <catch2/catch_test_macros.hpp>

#include "solution.hpp"

TEST_CASE("Problem 17", "[p0017]") {
CHECK(leetcode::p0017::solve("").empty());
CHECK(leetcode::p0017::solve("2") == std::vector<std::string>{"a", "b", "c"});
CHECK(leetcode::p0017::solve("23") ==
std::vector<std::string>{"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"});
}
48 changes: 0 additions & 48 deletions swift/17.swift

This file was deleted.

Loading