#1309
Decrypt String from Alphabet to Integer Mapping
EasyStringHash 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 approach involves scanning the string from right to left. This allows us to easily check for the presence of a '#' character and decode the string in a single pass, making it more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty result string.
- 2Step 2: Start iterating from the end of the string.
- 3Step 3: If the current character is '#', decode the two preceding characters as a two-digit number; otherwise, decode the current character as a single-digit number.
solution.py11 lines
1def decrypt(s):
2 result = ''
3 i = len(s) - 1
4 while i >= 0:
5 if s[i] == '#':
6 result += chr(int(s[i - 2:i]) + 96)
7 i -= 3
8 else:
9 result += chr(int(s[i]) + 96)
10 i -= 1
11 return result[::-1]ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the string. The space complexity is O(n) due to the space used for the result string.
- 1Scanning from right to left allows for efficient decoding.
- 2Recognizing patterns in the input string helps in determining the mapping.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.