call(back)
Algorithms & Data StructuresmediumSign in to star problems

Decrypt to Dictionary Words

An encrypter maps each character in keys (distinct lowercase letters) to the two-character string at the same index of values; several keys may share a value. A word is encrypted by replacing every character with its value and concatenating.

Given keys, values, a dictionary of candidate words and a ciphertext word, return every distinct dictionary word whose encryption is exactly word, sorted alphabetically. A dictionary word containing a character outside keys can never match.

keys = ["a", "b", "c", "d"], values = ["ei", "zf", "ei", "am"]
dictionary = ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]
word = "eizfeiam"  ->  ["abad", "abcd"]     // a and c both encrypt to "ei"
word = "eiam"      ->  []

The interviewer asked for depth-first search with backtracking over the two-character chunks, and then why DFS fits and what exactly is undone on the way back. Up to 26 keys, 100 dictionary words of length up to 100, and a ciphertext of even length up to 200.

Hints

Hint 1

Build the reverse map from each two-character value to the list of keys that produce it. Decoding is a walk over the ciphertext two characters at a time, branching on that list.

Hint 2

Backtracking: push a key, recurse on the rest of the ciphertext, pop. Prune when a chunk has no keys, and only check the dictionary at the end, with a Set for the lookup.

Hint 3

The branching can explode on adversarial inputs; encrypting each dictionary word once and comparing to the ciphertext is the linear alternative, and a good thing to mention after the DFS.

Topics

Asked at

Similar Problems6