Implement String Encryption and Decryption
Company: Duolingo
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of string encoding and mapping, including handling non-bijective character-to-code relationships and performing dictionary-based reverse lookups for decryption.
Constraints
- 1 <= len(keys) == len(codes) <= 26
- All entries in `keys` are distinct lowercase letters represented as 1-character strings
- 0 <= len(dictionary) <= 10^4 and 0 <= len(operations) == len(arguments) <= 10^4
- 1 <= len(codes[i]) <= 10
- The total length of all dictionary words and all operation arguments is at most 2 * 10^5
Examples
Input: (['a', 'b', 'c', 'd'], ['ei', 'zf', 'ei', 'am'], ['abcd', 'acbd', 'adbc', 'badc', 'dacb', 'cadb', 'cbda', 'abad'], ['encrypt', 'decrypt', 'encrypt', 'decrypt'], ['abcd', 'eizfeiam', 'badc', 'eiam'])
Expected Output: ['eizfeiam', ['abcd', 'abad'], 'zfeiamei', []]
Explanation: `encrypt('abcd')` becomes `ei + zf + ei + am = 'eizfeiam'`. Both `'abcd'` and `'abad'` encrypt to `'eizfeiam'`, so the decrypt query returns them in dictionary order. `'badc'` encrypts to `'zfeiamei'`. No dictionary word encrypts to `'eiam'`.
Input: (['a', 'b'], ['x', 'yy'], ['ab', 'ba', 'aa', 'ab', 'c'], ['encrypt', 'encrypt', 'decrypt', 'decrypt'], ['abc', 'ba', 'xyy', ''])
Expected Output: ['', 'yyx', ['ab', 'ab'], []]
Explanation: `'abc'` cannot be encrypted because `'c'` has no mapping, so the result is `''`. `'ba'` becomes `'yyx'`. The ciphertext `'xyy'` matches both occurrences of `'ab'`, and duplicates must be preserved. No dictionary word encrypts to the empty string.
Input: (['a', 'b', 'c'], ['m', 'm', 'n'], ['a', 'b', 'c', 'ab', 'ba', 'ac'], ['decrypt', 'encrypt', 'decrypt'], ['m', 'ac', 'mm'])
Expected Output: [['a', 'b'], 'mn', ['ab', 'ba']]
Explanation: Both `'a'` and `'b'` map to `'m'`, so decrypting `'m'` returns `['a', 'b']`. `'ac'` encrypts to `'mn'`. The ciphertext `'mm'` matches `'ab'` and `'ba'`.
Hints
- Build a direct mapping from each character in `keys` to its encrypted code so that encrypting one word is just a linear scan.
- For fast decryption, encrypt every dictionary word once up front and group words by their ciphertext. Then each decrypt query becomes a hash map lookup.