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 s of lowercase English letters, remove letters so that every letter in s is left exactly once. The letters you keep stay in their original order. Among all the strings you can get this way, return the one that comes first in dictionary order.

Example 1
Input: s = "bcabc"
Output: "abc"
Example 2
Input: s = "cbacdcbc"
Output: "acdb"
Solution

The Idea

Imagine the letters of "bcabc" written on a strip of paper. You may cross letters out, but you may not move them. There are two b's, two c's and a single a, so one b and one c must go. Which copies you cross out changes the word that is left: crossing out the last b and c leaves "bca", while crossing out the first ones leaves "abc".

Four different words can be left this way: "abc", "bac", "bca" and "cab". Which one comes first? Words are compared the way a dictionary orders them: find the first position where two words differ, and the word with the earlier letter there comes first. This is also called lexicographic order. "abc" starts with a, so it beats the other three and is the answer.

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", one position at a time, with positions counted from 0.

Reading cbacdcbc left to right. At position 1, b drops c because another c comes at 7. At position 2, a drops b because another b comes at 6. c and d are added. At position 6, d is bigger than b, but no d comes later, so d is kept and b goes after it. The kept letters end as acdb.

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, the expected output.

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" gives 7 different words. If each of the 26 letters appeared 4 times, there would be 426, about 4.5 × 1015, ways to choose which copies to keep. The left-to-right reading makes one pass instead.

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", the last a is at 2, the last b at 6, the last c at 7 and the last d at 4. At position 6, the last d is at 4, which is already behind us, so d never comes back.

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...", which comes after "ac...". So a letter that is already kept is simply skipped.

Java Solution

The method removeDuplicateLetters works in these steps:

  1. First, record the last position of every letter in an array last of 26 numbers, one for each letter from a to z. The entry for a letter c is last[c - 'a'].
  2. Hold the kept letters in a StringBuilder named stack, and use a boolean array used that marks which letters are in it right now.
  3. Read s with a loop over the positions i. If the letter c at position i is already marked in used, skip it.
  4. Otherwise, an inner while loop looks at the last kept letter, top. It stops when top is smaller than c, or when last[top - 'a'] < i, which means no copy of top comes later. If neither holds, it deletes top from stack and clears its mark in used.
  5. Append c to stack and mark it in used.
  6. When the loop over s is done, return the letters in stack as a string.

The main method runs both examples, a string of one repeated letter, a string with no repeats, a single letter, and two strings where letters are skipped or kept in place.

Java
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:

Output
"bcabc" -> "abc"
"cbacdcbc" -> "acdb"
"aaaa" -> "a"
"cba" -> "cba"
"z" -> "z"
"abacb" -> "abc"
"bbcaac" -> "bac"

Look at "cba" -> "cba". The a is smaller than both letters before it, yet nothing is dropped, because no letter appears twice and each one must stay. In "abacb" -> "abc", the second a and the second b are skipped, since a copy of each is already kept.

The last line shows a drop that stops partway. In "bbcaac", the a at position 3 drops c, because another c comes at position 5. The new last kept letter is b, also bigger than a, but the last b is at position 1, so b stays and the answer is "bac".

The check on last is what keeps every letter in the answer. A version that drops every bigger kept letter without that check turns "cba" into "a" and "cbacdcbc" into "abc", losing the d.

Complexity

The work is one pass to fill last, then one pass over s in which each letter is appended once at most and dropped only after being appended.

  • Time: O(n), because each of the n letters of s is appended to stack at most once, and every drop removes a letter appended earlier, so there are at most n drops.
  • Space: O(1) besides the result, because last and used have 26 entries each, and stack holds at most one copy of each of the 26 letters.

Dropping bigger letters from the end of a stack when a smaller one arrives is the pattern of a monotonic stack; this problem adds one condition, that the dropped letter comes back later.