#1957
Delete Characters to Make Fancy String
EasyStringTwo PointersSliding Window
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 uses a single pass through the string while keeping track of consecutive characters. This allows us to build the result string efficiently without unnecessary checks.
⚙️
Algorithm
4 steps- 1Step 1: Initialize an empty result string and a count variable.
- 2Step 2: Iterate through each character of the input string.
- 3Step 3: For each character, check if it is the same as the last character added to the result. If it is, increase the count; otherwise, reset the count.
- 4Step 4: If the count is less than 3, append the character to the result.
solution.py11 lines
1def makeFancyString(s):
2 result = ''
3 count = 1
4 for i in range(len(s)):
5 if i > 0 and s[i] == s[i - 1]:
6 count += 1
7 else:
8 count = 1
9 if count < 3:
10 result += s[i]
11 return resultℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the string, and the space complexity is O(n) due to the storage of the result string.
- 1To maintain a fancy string, we only need to ensure that no character appears three times consecutively.
- 2Using a single pass through the string is more efficient than checking all substrings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.