#3163
String Compression III
MediumStringTwo PointersString Manipulation
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 uses a single pass through the string to count consecutive characters and build the compressed string. This is efficient because it reduces the number of iterations needed, resulting in a linear time complexity.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty result string `comp` and a count variable.
- 2Step 2: Iterate through the string while counting consecutive characters.
- 3Step 3: When a different character is encountered or the end of the string is reached, append the count and character to `comp`, and reset the count.
solution.py10 lines
1def compress(word):
2 comp = ''
3 count = 1
4 for i in range(1, len(word) + 1):
5 if i < len(word) and word[i] == word[i - 1]:
6 count += 1
7 else:
8 comp += str(min(count, 9)) + word[i - 1]
9 count = 1
10 return compℹ
Complexity note: The time complexity is O(n) because we make a single pass through the string. The space complexity is O(n) due to the storage used for the compressed string.
- 1Count consecutive characters efficiently.
- 2Use string builders for better performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.