JAVA Solution | Stack
Please upvote this solution as well as this :D\n\nclass Solution {\n    public String smallestSubsequence(String s) {\n        int n = s.length();\n        bool
### Please upvote this solution as well as *[this](https://leetcode.com/problems/remove-duplicate-letters/discuss/2687478/JAVA-Solution-or-Stack)* :D\n```\nclass Solution {\n    public String smallestSubsequence(String s) {\n        int n = s.length();\n        boolean[] visited = new boolean[26];\n        int[] lastIndex = new int[26];\n\n        for (int i = 0; i < n; i++) {\n            lastIndex[s.charAt(i) - \'a\'] = i;\n        }\n\n        Stack<Integer> stack = new Stack<>();\n\n        for (int i = 0; i < n; i++) {\n            int c = s.charAt(i) - \'a\';\n\n            if(visited[c]) continue;\n            visited[c] = true;\n\n            while (!stack.isEmpty() && stack.peek() > c && lastIndex[stack.peek()] > i) {\n                visited[stack.pop()] = false;\n            }\n\n            stack.push(c);\n        }\n\n        StringBuilder ans = new StringBuilder();\n\n        for (Integer i : stack) {\n            ans.append((char)(i + \'a\'));\n        }\n\n        return ans.toString();\n    }\n}\n\n// TC: O(n), SC: O(n)\n```
['Stack', 'Java']