Encrypt and Decrypt Strings
Build a small substitution cipher where every letter turns into a two-letter code. The constructor receives three lists:
keys: distinct lowercase letters the cipher can handle.values:keys[i]is written asvalues[i]. Each value has two letters, and several keys may share the same value.dictionary: the only words that count as real plaintext. All dictionary words are different.
encrypt(word) replaces every letter with its code and returns the result, or "" as soon as a letter has no key.
decrypt(word) returns how many dictionary words encrypt to exactly that string. A two-letter chunk that is no key's value matches nothing, so the count is 0.
Several keys can share one code, so a code does not always point back to a single letter.
Example
keys = ["n", "o", "m"]
values = ["cd", "ab", "ab"]
dictionary = ["mn", "on", "nm"]
encrypt("nom") → "cdabab"
encrypt("mxn") → ""
decrypt("abcd") → 2
decrypt("cdab") → 1Both mn and on encrypt to abcd. The letter x has no key, so encrypting mxn returns an empty string.
You're building a tiny cipher where each letter becomes a two-letter code, then answering the reverse question: how many approved words could have produced this coded string? Interviewers love it because the two directions look symmetric until you try to make the second one fast. The classic trap is assuming every code points back to exactly one letter. Don't let the Hard label intimidate you; the core idea is simpler than it looks.
Examples
You write
Encrypter: encrypt(word: str), decrypt(word: str)
Example 1
- Input
- Encrypter(["n","o","m"], ["cd","ab","ab"], ["mn","on","nm"]), encrypt("nom") => "cdabab", decrypt("abcd") => 2, decrypt("cdab") => 1, encrypt("mxn") => ""
- returns
- ["cdabab", 2, 1, ""]
Example 2
- Input
- Last letter has no key: encrypt("kab") => "" while "kaa" and "ak" still work
- returns
- ["", "xyzwzw", "", "zwxy"]
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsStrings
I reach for it when
- The input is text and the answer is a count, a substring or a new string.
- You need to compare, reverse or rebuild characters.
Say this before you type. Say which array pattern the string is hiding before you touch a character.
All 51 Strings problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit, and to talk with her for one hour. After that, talking comes with the $79 pack. Anyone can open the editor and run their code.