Delete Characters to Make Fancy String

Updated on 16 May, 2025
Delete Characters to Make Fancy String header image

Problem Statement

The requirement of a fancy string is that it must not have three consecutive characters that are the same. Given an input string s, the task is to transform s into a fancy string by deleting the fewest characters possible. After making the required deletions, the resulting string should be returned. According to the problem constraints, it is guaranteed that a unique solution exists for each input.

Examples

Example 1

Input:

s = "Vuuultr"

Output:

"Vuultr"

Explanation:

Remove an 'u' from the first group of 'u's to create "Vuultr".
No three consecutive characters are equal, so return "Vuultr".

Example 2

Input:

s = "aaabaaaa"

Output:

"aabaa"

Explanation:

Remove an 'a' from the first group of 'a's to create "aabaaaa".
Remove two 'a's from the second group of 'a's to create "aabaa".
No three consecutive characters are equal, so return "aabaa".

Example 3

Input:

s = "aab"

Output:

"aab"

Explanation:

No three consecutive characters are equal, so return "aab".

Constraints

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

Approach and Intuition

Here's an outline of our approach to solving this problem and the rationale behind it:

  1. The primary objective is to ensure no three consecutive characters in the string s are identical. To achieve this, we iterate through the string and keep a count of the sequence length for each consecutive group of characters.

  2. As we traverse the string:

    • Increment a count each time the current character matches the previous one.
    • If a character does not match the previous one, reset this count.
    • If the count reaches three, it indicates a violation of the "fancy" requirement. Therefore, skip adding this character to the result.
  3. Updating the result string:

    • If the character count is less than three, append it to the result string.
    • If the count reaches three, simply avoid adding the current character. This effectively removes excessive characters that make parts of the string non-fancy.

Why this approach works?

  • By keeping track of how many times the current character has been consecutively repeated and only adding it to the result if it doesn't form a triplet, we're able to strip out the minimal number of characters to meet the problem's requirements.
  • The goal is not to just delete characters blindly but to do so strategically—only if they contribute to making a triplet or larger group of identical consecutive characters.

Efficiency Considerations

  • Given the constraint (1 <= s.length <= 105), our approach operates in linear time relative to the length of s, making a single pass through the string with constant-time checks and updates at each step—this is efficient and scalable for inputs near the upper limit of the constraint.
  • The space complexity is also linear as it potentially involves storing a new string almost equal to the size of the original during processing.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    string transformString(string str) {
        if (str.length() < 3) return str;
        int currentIndex = 2;
        for (int i = 2; i < str.size(); ++i) {
            if (str[i] != str[currentIndex - 1] || str[i] != str[currentIndex - 2]) {
                str[currentIndex++] = str[i];
            }
        }
        str.resize(currentIndex);
        return str;
    }
};

The provided C++ solution resolves the problem of deleting characters to create a "fancy string," where no three consecutive characters are the same. It defines a class Solution with a member function transformString that modifies the input string according to specified constraints.

Examine the function's working:

  • Initially, check if the string's length is less than 3, in which case it directly returns the string as it already satisfies the required condition.
  • Assign the value 2 to currentIndex, starting the check from the third character of the string.
  • Iterate through the string starting from the third character using a for loop. Compare each character with the two preceding it.
  • If the current character differs from the previous two, place it in the next position indicated by currentIndex and increment currentIndex.
  • After iterating through the string, resize the string to currentIndex to remove the extra characters that were shifted but not overwritten.
  • Return the modified string, now free from any sequences of three identical consecutive characters.

This approach ensures efficient in-place modification of the string with linear time complexity relative to the size of the input, optimizing both time and space usage.

java
class Solution {

    public String createUniqueString(String input) {
        // Direct return for small strings
        if (input.length() < 3) {
            return input;
        }

        StringBuilder result = new StringBuilder();
        // Initialize result with the first two chars
        result.append(input.charAt(0)).append(input.charAt(1));

        // Traverse starting from third character
        for (int index = 2; index < input.length(); ++index) {
            // Check conditions to avoid three consecutive same chars
            if (
                input.charAt(index) != result.charAt(result.length() - 1) ||
                input.charAt(index) != result.charAt(result.length() - 2)
            ) {
                result.append(input.charAt(index));
            }
        }

        // Return the processed string
        return result.toString();
    }
}

The provided Java code defines a method, createUniqueString, designed to remove consecutive characters from a string to prevent any three characters from being identical consecutively. This makes the string "fancy" by the given problem's definition. The methodology outlined in the code operates as follows:

  • It immediately returns short strings (less than 3 characters) since they inherently meet the criterion.
  • A StringBuilder variable result is initialized with the first two characters of the input string.
  • Starting from the third character of the input string, the algorithm iterates over each character and appends it to result only if it does not form a set of three consecutive identical characters with the previously added characters in result.
  • Finally, the StringBuilder object result is converted to a string and returned.

The method ensures that long strings are elegantly reduced by removing unwanted repetitions, thereby following the constraints of creating a "fancy" string efficiently. The solution makes use of the StringBuilder class to dynamically construct the resulting string efficiently, which offers performance benefits over using regular string concatenation in a loop.

python
class Solution:
    def createUniqueString(self, input_string: str) -> str:
        if len(input_string) < 3:
            return input_string

        character_list = list(input_string)
        valid_length = 2

        for pos in range(2, len(input_string)):
            if character_list[pos] != character_list[valid_length - 1] or character_list[pos] != character_list[valid_length - 2]:
                character_list[valid_length] = character_list[pos]
                valid_length += 1

        return "".join(character_list[:valid_length])

The provided Python solution aims to transform a given string into a "fancy string" which, as defined by the problem, is a string that doesn't contain three identical consecutive characters. Here’s how the solution works:

  • Start by checking if the input string is less than three characters long. If so, return it as is because it cannot have three identical consecutive characters.
  • Convert the string into a list of characters, character_list, to manipulate the contents easily.
  • Initialize valid_length to 2, representing the length of the new string that adheres to the fancy string criteria.
  • Iterate over the string starting from the third character (index position 2).
  • Within the loop, check if the current character does not match the last two characters added to the processed result (character_list[valid_length - 1] and character_list[valid_length - 2]). If the condition is true, update the character at the valid_length index and increment valid_length.
  • After completing the loop, concatenate the characters in character_list up to valid_length to form the resultant string.

This approach efficiently handles the removal of undesirable characters by rebuilding the string incrementally, ensuring it meets the criteria of not having three consecutive identical characters, hence making it "fancy".

Comments

No comments yet.