Delete Characters to Make Fancy String - Problem
Make Your String Fancy!

A fancy string is one where no three consecutive characters are the same. Your mission is to transform any given string into a fancy string by removing the minimum possible number of characters.

Given a string s, you need to:
• Remove characters strategically to ensure no three consecutive characters are identical
• Minimize the number of deletions
• Return the resulting fancy string

Example: The string "aaabaaaa" becomes "aabaa" by removing 3 characters.

The solution is guaranteed to be unique - there's only one optimal way to make the string fancy!

Input & Output

example_1.py — Basic Case
$ Input: s = "leeetcode"
Output: "leetcode"
💡 Note: Remove one 'e' from the triple 'eee' to make it fancy. The string becomes "leetcode" with no three consecutive identical characters.
example_2.py — Multiple Triplets
$ Input: s = "aaabaaaa"
Output: "aabaa"
💡 Note: Remove one 'a' from "aaa" and two 'a's from "aaaa" at the end. This gives us "aabaa" which has no three consecutive identical characters.
example_3.py — Already Fancy
$ Input: s = "aab"
Output: "aab"
💡 Note: The string is already fancy (no three consecutive identical characters), so no deletions are needed.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists only of lowercase English letters
  • The answer is guaranteed to be unique

Visualization

Tap to expand
🎉 The Fancy Party Guest ListNo three consecutive guests with the same name!Arriving Guests: A-A-A-B-A-A-A-AAAABAAAA🪑 Seated Guests (Final Result)AABAALegend:Seated (different name or safe)Seated (same name but safe)Asked to wait (would violate rule)Result: "AABAA" (3 guests asked to wait)💡 Greedy approach: Always seat guests unless it creates three consecutive with same name
Understanding the Visualization
1
Guests Arrive
Process each guest (character) in arrival order
2
Check Seating
Look at the last two seated guests
3
Seat or Wait
If the last two have the same name as the current guest, ask them to wait (skip)
4
Maintain Fancy
This ensures no three consecutive guests ever have the same name
Key Takeaway
🎯 Key Insight: The greedy approach works because removing the third occurrence of any consecutive triplet is always optimal - it preserves the maximum number of characters while ensuring the fancy property.
Asked in
Amazon 45 Google 35 Microsoft 25 Meta 20
42.3K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen