LeetCode 1081: Smallest Subsequence of Distinct Characters Solution

Master LeetCode problem 1081 (Smallest Subsequence of Distinct Characters), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1081. Smallest Subsequence of Distinct Characters

Problem Explanation

Explanation

To solve this problem, we will use a stack to keep track of characters in the final subsequence. The idea is to iterate through the input string and for each character, we check if it is already in the stack. If it is not in the stack, we pop characters from the stack if they are greater than the current character and they will appear later in the string. Then, we push the current character onto the stack.

After processing all characters, the stack will contain the lexicographically smallest subsequence of distinct characters.

Time complexity: O(n), where n is the length of the input string s.
Space complexity: O(n)

Solution Code

class Solution {
    public String smallestSubsequence(String s) {
        Stack<Character> stack = new Stack<>();
        boolean[] visited = new boolean[26];
        int[] lastOccur = new int[26];
        
        for (int i = 0; i < s.length(); i++) {
            lastOccur[s.charAt(i) - 'a'] = i;
        }
        
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!visited[c - 'a']) {
                while (!stack.isEmpty() && stack.peek() > c && lastOccur[stack.peek() - 'a'] > i) {
                    visited[stack.pop() - 'a'] = false;
                }
                stack.push(c);
                visited[c - 'a'] = true;
            }
        }
        
        StringBuilder sb = new StringBuilder();
        for (char ch : stack) {
            sb.append(ch);
        }
        
        return sb.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1081 (Smallest Subsequence of Distinct Characters)?

This page provides optimized solutions for LeetCode problem 1081 (Smallest Subsequence of Distinct Characters) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1081 (Smallest Subsequence of Distinct Characters)?

The time complexity for LeetCode 1081 (Smallest Subsequence of Distinct Characters) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1081 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1081 in Java, C++, or Python.

Back to LeetCode Solutions