Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Greedy

Smallest Subsequence of Distinct Characters

Medium · Greedy · Asked at Google, Amazon, Bloomberg, Apple

Print the lexicographically smallest subsequence of s that contains every distinct letter of s exactly once.

Input

A single line with the string (lowercase letters).

Output

The smallest such subsequence.

Constraints

Build the answer on a stack. Skip a letter already in the stack. Otherwise, while the top is larger than the letter and the top appears again later, pop it (a later copy can be used). Then push the letter.

Example 1

Input

bcabc

Output

abc

Example 2

Input

cbacdcbc

Output

acdb

Hints

  1. Build the answer left to right, keeping it on a stack.
  2. A bigger letter on top can be thrown away if it appears again later — a smaller letter in front is always better.
  3. Never add a letter that is already in the stack.

Approach

Record each letter's last index. For each position: skip the letter if it is already in the stack. Otherwise, while the top of the stack is larger than it and the top letter occurs again later, pop the top (we will pick it up later, behind the smaller letter). Push the letter. The stack ends with each letter exactly once, in the smallest possible order.

Complexity: O(n) time · O(26) extra space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin >> s;
    int last[26] = {0};
    for (int i = 0; i < (int) s.size(); i++) last[s[i] - 'a'] = i;
    string st;
    bool in[26] = {false};
    for (int i = 0; i < (int) s.size(); i++) {
        char c = s[i];
        if (in[c - 'a']) continue;
        while (!st.empty() && st.back() > c && last[st.back() - 'a'] > i) {
            in[st.back() - 'a'] = false;
            st.pop_back();
        }
        st.push_back(c);
        in[c - 'a'] = true;
    }
    cout << st << "\n";
    return 0;
}

Python solution

s = input().strip()
last = {c: i for i, c in enumerate(s)}
stack = []
seen = set()
for i, c in enumerate(s):
    if c in seen:
        continue
    while stack and stack[-1] > c and last[stack[-1]] > i:
        seen.discard(stack.pop())
    stack.append(c)
    seen.add(c)
print("".join(stack))

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
        int[] last = new int[26];
        for (int i = 0; i < s.length(); i++) last[s.charAt(i) - 'a'] = i;
        StringBuilder st = new StringBuilder();
        boolean[] in = new boolean[26];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (in[c - 'a']) continue;
            while (st.length() > 0 && st.charAt(st.length() - 1) > c && last[st.charAt(st.length() - 1) - 'a'] > i) {
                in[st.charAt(st.length() - 1) - 'a'] = false;
                st.deleteCharAt(st.length() - 1);
            }
            st.append(c);
            in[c - 'a'] = true;
        }
        System.out.println(st);
    }
}

Solve Smallest Subsequence of Distinct Characters online · All practice problems