#2325
Decode the Message
EasyHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution efficiently constructs the mapping in a single pass through the key and then decodes the message in another pass, making it much faster than the brute force approach.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty mapping and a variable to track the next available letter in the alphabet.
- 2Step 2: Iterate through the key, adding each unique character to the mapping until all 26 letters are mapped.
- 3Step 3: Create the decoded message by replacing each character in the message using the mapping.
solution.py14 lines
1# Full working Python code
2key = 'the quick brown fox jumps over the lazy dog'
3message = 'vkbs bs t suepuv'
4
5mapping = {}
6alpha = 'abcdefghijklmnopqrstuvwxyz'
7next_char = 0
8for char in key:
9 if char != ' ' and char not in mapping:
10 mapping[char] = alpha[next_char]
11 next_char += 1
12
13decoded_message = ''.join(mapping.get(char, char) for char in message)
14print(decoded_message)ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the key and another pass through the message, making it efficient. The space complexity is O(1) since the mapping size is constant (26 letters).
- 1The mapping is based on the first appearance of characters in the key.
- 2Spaces are preserved in the message and do not affect the mapping.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.