Python and Java solution.
Steps:\n1. a dictionary/map with Last occurance of each character in the String.\n2. a stack that will help us keep track of the last inserted Character.\n3. fo
**Steps:**\n1. a dictionary/map with Last occurance of each character in the String.\n2. a stack that will help us keep track of the last inserted Character.\n3. for each character, we check if we have pushed it into the stack earlier, we use a set for Fast Lookups.\n4. if the character is present in SET do nothing with that character.\n5. otherwise, check if the character at the top of the stack is greater than the current Character (to maintain lexicographical order, Eg: b is greater than a).\n6. if so, we pop the Greater character and we push the current smaller character.\n8. one think to worry about before we pop the top character is to check if we will see the top character again later in the string, we do this by checking the last Occurance Dict/Map.\n7. finally we convert the stack/list into a string.\n\n**Python:**\n```\nclass Solution:\n    def removeDuplicateLetters(self, s: str) -> str:\n        lastPos = {}\n        for i in range(len(s)): lastPos[s[i]] = i\n        stack = []\n        seen= set()\n        for i in range(len(s)):\n            if s[i] in seen: continue\n            while stack and stack[-1] > s[i] and lastPos[stack[-1]] > i:\n                p = stack.pop()\n                seen.remove(p)\n            stack.append(s[i])\n            seen.add(s[i])\n        return "".join(stack)\n```\n\n**Java:**\n```\nclass Solution {\n    public String smallestSubsequence(String s) {\n        Map<Character, Integer> lastPos = new HashMap<>();\n        for(int i=0; i<s.length(); ++i) lastPos.put(s.charAt(i), i);\n        Stack<Character> stack = new Stack<>();\n        Set<Character> seen = new HashSet<>();\n        for(int i=0; i<s.length(); ++i){\n            char curr = s.charAt(i);\n            if(seen.contains(curr)) continue;\n            while(!stack.isEmpty() && stack.peek() > curr && lastPos.get(stack.peek()) > i){\n                char p = stack.pop();\n                seen.remove(p);\n            }\n            stack.add(curr);\n            seen.add(curr);\n        }\n        String ans = "";\n        for(char c: stack) ans+=c;\n        return ans;\n    }\n}\n```
[]