All problems

Problem 228

Remove Duplicate Letters

Medium · 20 pts · String, Stack, Greedy, Monotonic Stack

Problem

You are given a string S. Remove letters so that every distinct letter of S appears exactly once in the result. The result must keep the remaining letters in their original order (it must be a subsequence of S), and among all such results it must be the lexicographically smallest. Use a greedy stack. For each letter not already in the stack, pop larger letters from the top as long as they appear again later in S (so they can be taken later), then push the letter. Knowing the last position of each letter makes the check easy.

Input

A single string S of lowercase English letters.

Output

Print the resulting string.

Constraints

1 <= |S| <= 10000

Example input

bcabc

Example output

abc

Explanation

From "bcabc", every letter a, b and c must appear once. Taking a from the middle and b and c after it gives "abc", which is a subsequence of S and the smallest possible order.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Add Binary Next: Longest Happy Prefix