Delete Characters to Make Fancy String — LeetCode 1957 Python Solution

EasyString
Problem
#1957
Pattern
Hash Map
Reading time
2 min

The 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.

Example

Input
s = "leeetcode"
Output
"leetcode"
Explanation
Remove an 'e' from the first group of 'e's to create "leetcode".

Python solution

Python
class Solution:
    def makeFancyString(self, s: str) -> str:
        ans = []
        for i, c in enumerate(s):
            if i < 2 or c != s[i - 1] or c != s[i - 2]:
                ans.append(c)
        return "".join(ans)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1957. Delete Characters to Make Fancy String is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1957. Delete Characters to Make Fancy String?
LeetCode 1957. Delete Characters to Make Fancy String is rated Easy on LeetCode.
What is the time complexity of LeetCode 1957. Delete Characters to Make Fancy String?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 1957. Delete Characters to Make Fancy String?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1957. Delete Characters to Make Fancy String cover?
LeetCode 1957. Delete Characters to Make Fancy String is tagged String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview