Problem Description
Given a string s, delete the minimum number of characters such that no three consecutive characters are the same. The resulting string must be "fancy" where no three consecutive characters are equal. It can be shown that the answer is unique.
Key Insights
- The goal is to avoid any group of three identical characters in sequence.
- A single pass through the string is sufficient by checking the last two characters of the result.
- If the current character is the same as the last two in the result string, skip it; otherwise, add it.
- This greedy approach ensures the minimal number of deletions.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string, because we process each character once. Space Complexity: O(n), for storing the output result which in worst case is nearly the same size as the input.
Solution
We use a greedy algorithm with a simple iteration over the string. The data structure used is a list (or equivalent in other languages) that acts as a dynamic array to build the final string. For each character in the input string, we check if it would form three consecutive identical characters by comparing against the last two characters stored in the result. If it would, we skip adding it; otherwise, we append it. This ensures that the resulting string is the “fancy” version with minimal deletions.