Encrypt and Decrypt Strings - 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.
You should implement a data structure that can encrypt or decrypt a 0-indexed string.
Encryption Process:
- For each character
cin the string, we find the indexisatisfyingkeys[i] == cinkeys. - Replace
cwithvalues[i]in the string.
Note that in case a character of the string is not present in keys, the encryption process cannot be carried out, and an empty string "" is returned.
Decryption Process:
- For each substring
sof length 2 occurring at an even index in the string, we find anisuch thatvalues[i] == s. If there are multiple validi, we choose any one of them. This means a string could have multiple possible strings it can decrypt to. - Replace
swithkeys[i]in the string.
Implement the Encrypter class:
Encrypter(char[] keys, String[] values, String[] dictionary)Initializes the Encrypter class withkeys,values, anddictionary.String encrypt(String word1)Encryptsword1with the encryption process described above and returns the encrypted string.int decrypt(String word2)Returns the number of possible stringsword2could decrypt to that also appear indictionary.
Input & Output
Example 1 — Basic Encryption/Decryption
$
Input:
keys = ['a', 'b', 'c'], values = ["hj", "xy", "wz"], dictionary = ["ab", "bc"], operations = [["encrypt", "ab"], ["decrypt", "hjxy"]]
›
Output:
["hjxy", "1"]
💡 Note:
Encrypt 'ab': 'a'→"hj", 'b'→"xy", result "hjxy". Decrypt "hjxy": splits to "hj"+"xy" which could be 'a'+'b'="ab", and "ab" exists in dictionary, so count is 1.
Example 2 — Multiple Dictionary Matches
$
Input:
keys = ['a', 'b'], values = ["hj", "hj"], dictionary = ["aa", "bb"], operations = [["decrypt", "hjhj"]]
›
Output:
["2"]
💡 Note:
Decrypt "hjhj": both 'a' and 'b' map to "hj", so "hjhj" could decode to "aa" or "bb". Both exist in dictionary, so count is 2.
Example 3 — Invalid Encryption
$
Input:
keys = ['a', 'b'], values = ["hj", "xy"], dictionary = ["ab"], operations = [["encrypt", "ac"]]
›
Output:
[""]
💡 Note:
Encrypt 'ac': 'a'→"hj" but 'c' is not in keys array, so encryption fails and returns empty string.
Constraints
- 1 ≤ keys.length == values.length ≤ 26
- values[i].length == 2
- 1 ≤ dictionary.length ≤ 100
- 1 ≤ dictionary[i].length ≤ 100
- At most 200 calls will be made to encrypt and decrypt
Visualization
Tap to expand
Understanding the Visualization
1
Input
Keys ['a','b','c'], Values ["hj","xy","wz"], Dictionary ["ab","bc"]
2
Process
Build char↔code mappings and handle encrypt/decrypt operations
3
Output
Return encrypted strings or count of valid dictionary matches
Key Takeaway
🎯 Key Insight: Pre-encrypt all dictionary words to transform expensive decryption into O(1) lookup
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code