Delete Characters to Make Fancy String - Problem

A fancy string is a string where no three consecutive characters are equal.

Given a string s, delete the minimum possible number of characters from s to make it fancy.

Return the final string after the deletion. It can be shown that the answer will always be unique.

Input & Output

Example 1 — Basic Case
$ Input: s = "leeetcode"
Output: "leetcode"
💡 Note: Remove one 'e' from the three consecutive 'e's. The result is "leetcode" with no three consecutive characters equal.
Example 2 — Multiple Groups
$ Input: s = "aaabaaaa"
Output: "aabaa"
💡 Note: Remove one 'a' from "aaa" at start and two 'a's from "aaaa" at end. Result: "aabaa".
Example 3 — Already Fancy
$ Input: s = "aab"
Output: "aab"
💡 Note: No three consecutive characters are equal, so no deletion needed.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists only of lowercase English letters

Visualization

Tap to expand
Delete Characters to Make Fancy String INPUT Input String s: l e e e e t c o d e Indices: 0 1 2 3 4 5 6 7 8 Problem: No 3 consecutive chars can be equal. Issue detected: "eee" at index 1-3 (3 consecutive 'e's) = To be removed = Keep ALGORITHM STEPS 1 Initialize Stack Create empty result array to build output string 2 Iterate Characters For each char in input, check last 2 in stack 3 Check Condition If stack[-1] == stack[-2] == current: SKIP char 4 Add or Skip Otherwise: ADD char to result stack Stack after processing: [l,e,e,t,c,o,d,e] FINAL RESULT Output String: l e e t c o d e "leetcode" Characters removed: 1 (one extra 'e') Verification: - No "eee" substring - No 3 consecutive equal - Minimum deletions: OK FANCY OK Key Insight: The stack-like approach allows us to efficiently track the last two characters added. Before adding a new character, we check if it would create 3 consecutive equal characters. If so, we skip it. This ensures minimum deletions while maintaining the "fancy" property. Time: O(n), Space: O(n) TutorialsPoint - Delete Characters to Make Fancy String | Stack-like Approach
Asked in
Amazon 15 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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