Remove Duplicate Letters
Keep one copy of each letter, in the original order, so that the result comes first in dictionary order.
Given a string ss
Example 1
Output: "abc"
Example 2
Output: "acdb"
The Idea
Imagine the letters of "bcabc""bca""abc"
Four different words can be left this way: "abc""bac""bca""cab""abc"
So the first letter matters most, then the second, and so on, and we want small letters as early as possible. But we cannot throw a letter away freely, because every letter must stay once. When is it safe to give up a copy?
Read the string from left to right and collect the kept letters for the answer in order. When a new letter is smaller than the last kept letter, that last letter would be better further back. It may be dropped, but only if another copy of it comes later, so it can be kept again there. If no copy comes later, it has to stay.
Look at the picture below. It reads Example 2, "cbacdcbc"
At position 1, b is smaller than c, and another c comes at position 7, so the picture's row says drop c: another c comes at 7. Position 2 does the same to b. Then c and d are added, and at position 5 the c is skipped, because a c is already kept. In the row for position 6, b is smaller than d, but no d comes later, so d stays and b goes after it. The kept letters end as acdb
Notice that the kept letters only change at their right end: new letters are added there, and a drop always takes the last one. A list that is used this way is called a stack. Each step also takes what looks best right now, a smaller letter earlier, whenever that costs nothing later. Building the answer from such local choices, without trying the alternatives, is called a greedy choice.
Solution Approach
Four things need settling: why trying every result is too slow, how to tell that a letter comes back, when to drop the last kept letter, and what to do with a letter already kept.
Trying every result
Why not list every way to keep one copy of each letter and pick the smallest word? Even "cbacdcbc"
Knowing whether a letter comes back
How can we tell, at some position, whether a letter appears again later? Before the main pass, one quick pass records the last position of every letter. In "cbacdcbc"
When to drop the last kept letter
Why is a drop safe? If the last kept letter is bigger than the new letter and appears again later, the new letter takes its place, and that position of the answer gets a smaller letter. A smaller letter at an earlier position wins whatever follows, and the dropped letter can still be kept at its later copy.
After a drop, there is a new last kept letter, and the same check runs again. So one new letter can drop several kept letters, and it stops at the first one that is smaller or never comes back.
A letter that is already kept
What about a letter that is already kept, like the c at position 5? At that point the kept letters are a, c, d, so the letter right after the kept c is d. When d arrived, c was the last kept letter, and c had another copy later. Had d been smaller, it would have dropped c, so d must be bigger.
The same reasoning works for any kept letter we meet again: it has a later copy, so the letter right after it among the kept letters must be bigger. Swapping the kept c for the later copy would move d forward into its place and give "ad...""ac..."
Java Solution
The method removeDuplicateLetters
- First, record the last position of every letter in an array
of 26 numbers, one for each letter from a to z. The entry for a letterlast isc .last[c - 'a'] - Hold the kept letters in a
namedStringBuilder , and use astack arrayboolean that marks which letters are in it right now.used - Read
with a loop over the positionss . If the letteri at positionc is already marked ini , skip it.used - Otherwise, an inner
loop looks at the last kept letter,while . It stops whentop is smaller thantop , or whenc , which means no copy oflast[top - 'a'] < i comes later. If neither holds, it deletestop fromtop and clears its mark instack .used - Append
toc and mark it instack .used - When the loop over
is done, return the letters ins as a string.stack
The main
public class RemoveDuplicateLetters {
public static String removeDuplicateLetters(String s) {
int[] last = new int[26];
for (int i = 0; i < s.length(); i++) {
last[s.charAt(i) - 'a'] = i; // last position of each letter
}
boolean[] used = new boolean[26];
StringBuilder stack = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (used[c - 'a']) {
continue; // this letter is already kept
}
while (stack.length() > 0) {
char top = stack.charAt(stack.length() - 1);
if (top <= c || last[top - 'a'] < i) {
break; // top is smaller, or never comes back
}
stack.deleteCharAt(stack.length() - 1); // a later copy of top will be kept
used[top - 'a'] = false;
}
stack.append(c);
used[c - 'a'] = true;
}
return stack.toString();
}
public static void main(String[] args) {
String[] inputs = {"bcabc", "cbacdcbc", "aaaa", "cba", "z", "abacb", "bbcaac"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> \"" + removeDuplicateLetters(s) + "\"");
}
}
}
Running it prints:
"bcabc" -> "abc"
"cbacdcbc" -> "acdb"
"aaaa" -> "a"
"cba" -> "cba"
"z" -> "z"
"abacb" -> "abc"
"bbcaac" -> "bac"
Look at "cba" -> "cba""abacb" -> "abc"
The last line shows a drop that stops partway. In "bbcaac""bac"
The check on last"cba""a""cbacdcbc""abc"
Complexity
The work is one pass to fill lasts
- Time: O(n), because each of the n letters of
is appended tos at most once, and every drop removes a letter appended earlier, so there are at most n drops.stack - Space: O(1) besides the result, because
andlast have 26 entries each, andused holds at most one copy of each of the 26 letters.stack
Dropping bigger letters from the end of a stack when a smaller one arrives is the pattern of a