Encrypt and Decrypt Strings — LeetCode 2227 Python Solution
- Problem
- #2227
- Pattern
- Trie
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption.
Example
- Input
- ["Encrypter", "encrypt", "decrypt"]
- Output
- [null, "eizfeiam", 2]
- Explanation
- Encrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]);
Python solution
class Encrypter:
def __init__(self, keys: List[str], values: List[str], dictionary: List[str]):
self.mp = dict(zip(keys, values))
self.cnt = Counter(self.encrypt(v) for v in dictionary)
def encrypt(self, word1: str) -> str:
res = []
for c in word1:
if c not in self.mp:
return ''
res.append(self.mp[c])
return ''.join(res)
def decrypt(self, word2: str) -> int:
return self.cnt[word2]
# Your Encrypter object will be instantiated and called as such:
# obj = Encrypter(keys, values, dictionary)
# param_1 = obj.encrypt(word1)
# param_2 = obj.decrypt(word2)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n + m), where n and m are the lengths of \textit{keys} and \textit{dictionary}, respectively |
| Space | O(n + m) auxiliary |
Pattern: Trie
Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 2227. Encrypt and Decrypt Strings is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.
The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2227. Encrypt and Decrypt Strings?
- LeetCode 2227. Encrypt and Decrypt Strings is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2227. Encrypt and Decrypt Strings?
- The Python solution on this page runs in O(n + m), where n and m are the lengths of \textit{keys} and \textit{dictionary}, respectively.
- What is the space complexity of LeetCode 2227. Encrypt and Decrypt Strings?
- The Python solution on this page uses O(n + m) auxiliary space.
- What topics does LeetCode 2227. Encrypt and Decrypt Strings cover?
- LeetCode 2227. Encrypt and Decrypt Strings is tagged Design, Trie, Array, Hash Table and String on LeetCode.