Delete Characters to Make Fancy String (LeetCode 1957): Solution and Explanation
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
- Create an empty output builder.
- For each character
chofs: if the builder has at least two characters and both of the last two equalch, skipch. - Otherwise append
ch. - Return the builder as a string.
Step-by-step example
s = "leeetcode"
lis kept (output is too short to form a triple). Outputl.- The first
eis kept: the output ends inl. Outputle. - The second
eis kept: the output ends inle, notee. Outputlee. - The third
earrives while the output ends inee, so keeping it would makeeee. It is deleted. t,c,o,d,eall 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)1class Solution {
2 public String makeFancyString(String s) {
3 StringBuilder sb = new StringBuilder();
4 for (char ch : s.toCharArray()) {
5 int n = sb.length();
6 if (n >= 2 && sb.charAt(n - 1) == ch && sb.charAt(n - 2) == ch) {
7 continue;
8 }
9 sb.append(ch);
10 }
11 return sb.toString();
12 }
13}1class Solution {
2public:
3 string makeFancyString(string s) {
4 string out;
5 for (char ch : s) {
6 int n = out.size();
7 if (n >= 2 && out[n - 1] == ch && out[n - 2] == ch) {
8 continue;
9 }
10 out.push_back(ch);
11 }
12 return out;
13 }
14};Time and space complexity
O(n)
Each character is checked once against two output characters and appended at most once.
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]ands[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.