#2227
Encrypt and Decrypt Strings
HardArrayHash TableStringDesignTrieHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages hash maps for quick lookups during encryption and decryption, ensuring that we can efficiently find the corresponding values or keys without unnecessary iterations.
⚙️
Algorithm
3 steps- 1Step 1: Create a mapping from each character in keys to its corresponding value in values and vice versa using two hash maps.
- 2Step 2: For encryption, iterate through the input string and replace each character using the mapping. If a character is not found, return an empty string immediately.
- 3Step 3: For decryption, check every two-character substring in the encrypted string. Use the reverse mapping to find possible original characters and count how many valid combinations exist in the dictionary.
solution.py28 lines
1class Encrypter:
2 def __init__(self, keys, values, dictionary):
3 self.map = {keys[i]: values[i] for i in range(len(keys))}
4 self.reverse_map = {values[i]: keys[i] for i in range(len(values))}
5 self.dictionary = set(dictionary)
6
7 def encrypt(self, word1):
8 encrypted = []
9 for char in word1:
10 if char in self.map:
11 encrypted.append(self.map[char])
12 else:
13 return ""
14 return ''.join(encrypted)
15
16 def decrypt(self, word2):
17 count = 0
18 n = len(word2)
19 if n % 2 != 0:
20 return 0
21 possible_decryptions = set()
22 for i in range(0, n, 2):
23 if word2[i:i+2] in self.reverse_map:
24 possible_decryptions.add(self.reverse_map[word2[i:i+2]])
25 for original in possible_decryptions:
26 if original in self.dictionary:
27 count += 1
28 return countℹ
Complexity note: The time complexity is O(n) because we only iterate through the input string a limited number of times, and lookups in the hash maps are O(1). The space complexity is O(n) due to the storage of the mappings and the dictionary.
- 1Using hash maps allows for O(1) average time complexity for lookups, making both encryption and decryption efficient.
- 2Understanding the relationship between keys and values is crucial for both processes, as they are directly tied to how we encrypt and decrypt strings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.