Remove Duplicate Letters

This page explains Java solution to problem Remove Duplicate Letters using Stack data structure.

Problem Statement

Given a string which contains only lowercase letters, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Example 1:

Input: "bcabc"
Output: "abc"

Solution

If you have any suggestions in below code, please create a pull request by clicking here.

package com.vc.hard;

import java.util.*;

class RemoveDuplicateLetters {
    public String removeDuplicateLetters(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        HashSet<Character> set = new HashSet<>();

        //Last occurrence of character
        for(int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            map.put(ch, i);
        }

        Stack<Character> st = new Stack<>();
        for(int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if(!set.contains(ch)) {
                while(!st.isEmpty() && st.peek() > ch && map.get(st.peek()) > i) {
                    set.remove(st.pop());
                }
                st.push(ch);
            }
            set.add(ch);
        }

        StringBuilder str = new StringBuilder();
        while(!st.isEmpty()) {
            str.insert(0, st.pop());
        }
        return str.toString();
    }
}

Time Complexity

O(N) Where
N is total number of elements in an input string

Space Complexity

O(N) Where
N is total number of elements in an input string