The Indian Engineer

Problem 1957 Delete Characters to Make Fancy String

Posted on 4 mins

String

Problem Statement

Link - Problem 1957

Question

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.

 

Example 1:

Input: s = "leeetcode"
Output: "leetcode"
Explanation:
Remove an 'e' from the first group of 'e's to create "leetcode".
No three consecutive characters are equal, so return "leetcode".

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:

Solution

class Solution {
public:
    string makeFancyString(string& s) {
        for (int i = 2; i < s.size(); i++) {
            if (s[i] == s[i - 1] && s[i] == s[i - 2]) {
                s.erase(i, 1);
                i--;
            }
        }
        return s;
    }
};

Complexity Analysis

| Algorithm                                         | Time Complexity | Space Complexity |
| ------------------------------------------------- | --------------- | ---------------- |
| Single pointer traversal with string modification | O(n)            | O(1)             |

Explanation

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Easy difficulty.

Hints

What’s the optimal way to delete characters if three or more consecutive characters are equal?

If three or more consecutive characters are equal, keep two of them and delete the rest.


Similar Questions:

Title URL Difficulty
Find Maximum Removals From Source String https://leetcode.com/problems/find-maximum-removals-from-source-string Medium