Delete Characters to Make Fancy String (LeetCode 1957): Solution and Explanation

Easy
String

A string is fancy when no three consecutive characters are equal. Delete as few characters as possible from s to make it fancy and return the result.

Intuition

Split the string into runs of equal letters. Runs never interact: deleting inside one run cannot merge or break another, because neighbouring runs hold different letters. So each run can be fixed on its own.

A run of length k is fine as long as it has at most 2 letters, so it must lose exactly k - 2 letters when k > 2 and none otherwise. Since all letters in a run are identical, it does not matter which copies are deleted, and the answer is unique.

That turns into a simple streaming rule: while building the output, a new letter is refused only when the output already ends with two copies of it. The last two output characters are all the memory you need.

Approach: Greedy builder with a two-character check

  1. Create an empty output builder.
  2. For each character ch of s: if the builder has at least two characters and both of the last two equal ch, skip ch.
  3. Otherwise append ch.
  4. Return the builder as a string.

Step-by-step example

s = "leeetcode"
  1. l is kept (output is too short to form a triple). Output l.
  2. The first e is kept: the output ends in l. Output le.
  3. The second e is kept: the output ends in le, not ee. Output lee.
  4. The third e arrives while the output ends in ee, so keeping it would make eee. It is deleted.
  5. t, c, o, d, e all pass the check, giving "leetcode" with one deletion.

Code: Python, Java, C++

1class Solution:
2    def makeFancyString(self, s: str) -> str:
3        out = []
4        for ch in s:
5            if len(out) >= 2 and out[-1] == ch and out[-2] == ch:
6                continue
7            out.append(ch)
8        return ''.join(out)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is checked once against two output characters and appended at most once.

Space

O(n)

The output can be as long as the input. Apart from it, only a constant amount of memory is used.

Other approaches

Run-length counter (time O(n), space O(n))

Track the length of the current run instead of reading the builder: reset it to 1 when the letter changes, increase it otherwise, and append only while it is at most 2. Same complexity, and it avoids indexing into the builder.

Repeated deletion (time O(n^2), space O(n))

Search for a triple and delete one character, then repeat until none is left. It is correct but each deletion shifts the string, which costs O(n) and gives O(n^2) overall.

Common mistakes

  • Comparing with the input instead of the output. After a deletion the input still holds the dropped letter, so s[i-1] and s[i-2] can wrongly count it.
  • Deleting characters from the string in place inside a loop, which is quadratic and easy to get wrong with shifting indices.
  • Concatenating strings with += in a language with immutable strings; on a 100,000-character input that can time out. Use a builder.

Frequently asked questions

Why is the answer unique?

Each run of length k must keep exactly min(k, 2) copies of one letter, and copies of the same letter are indistinguishable, so every optimal deletion gives the same string.

Why is this greedy choice optimal?

It deletes a letter only when keeping it would definitely create a triple, and it deletes exactly k - 2 letters from every run longer than 2, which is the least any valid answer can delete.

Can this be done in O(1) extra space?

Apart from the output, yes. In languages with mutable character arrays you can write the kept characters forward with a write pointer and cut the array at the end.

What is the time and space complexity?

O(n) time and O(n) space for the output string.