πΉ Problem: 1957. Delete Characters to Make Fancy String
Difficulty: #Easy
Tags: #String
π Problem Summary
Given a string s
, remove the minimum number of characters such that there are no three consecutive characters that are the same. Return the resulting string.
β
The answer is guaranteed to be unique.
π§ My Thought Process
Brute Force Idea:
I initially tried to simulate the string modification by scanning it and usingpop(i)
whenever I found three repeating characters. But... yeah,pop()
on a list is O(n) if it's not at the end β and I was doing it potentiallyn
times. So... it timed out.-
Optimized Strategy:
I realized instead of deleting from the original string, I could build a new one from scratch:- Start with an empty result list.
- Loop through each character.
- Append the character only if the last two characters in the result are not equal to the current character.
This way, I never have three in a row β and all operations are fast (O(1)
per append/check).
- Algorithm Used: Simple greedy + string construction strategy.
βοΈ Code Implementation (Python)
class Solution:
def makeFancyString(self, s: str) -> str:
res = []
for c in s:
if len(res) >= 2 and res[-1] == res[-2] == c:
continue
res.append(c)
return ''.join(res)
β±οΈ Time & Space Complexity
- Time: O(n) β One pass through the string with constant time operations.
- Space: O(n) β To store the resulting string.
π§© Key Takeaways
- β Reversing your approach can turn a brute force into a greedy O(n) solution.
- π‘ Avoid modifying a list in-place with
pop(i)
inside a loop unless you're popping from the end. - π If a problem talks about "consecutive" characters, consider a sliding window of size 2 or 3.
π Reflection (Self-Check)
- [x] Could I solve this without help?
- [x] Did I write code from scratch?
- [x] Did I understand why it works?
- [x] Will I be able to recall this in a week?
π Related Problems
- [[3316 Find Maximum Removals From Source String]]
π Progress Tracker
Metric | Value |
---|---|
Day | 50 |
Total Problems Solved | 391 |
Confidence Today | π |
Leetcode Rating | 1572 |
Top comments (0)