KatInterview

316. Remove Duplicate Letters

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to remove duplicate letters from a string s such that the resulting string contains each original character exactly once. Among all possible resulting strings, we must find the one that is lexicographically smallest. For example, for s = "bcabc", the unique characters are 'a', 'b', 'c'. The possible subsequences are "abc", "bac", etc. The lexicographically smallest is "abc".

Solution

Remove Duplicate Letters in Python

class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        # last_occurrence[char] = index of last occurrence of char
        last_occurrence = {char: i for i, char in enumerate(s)}
        
        # Use a stack to build the result and a set to track chars in the stack
        stack = []
        seen = set()

        for i, char in enumerate(s):
            # If we have already included this character in an optimal position, skip it.
            if char in seen:
                continue
            
            # This is the greedy part.
            # If the current character is smaller than the character at the top of the stack,
            # and the top character will appear again later in the string,
            # we can pop the top character. This might lead to a lexicographically smaller result.
            while stack and char < stack[-1] and last_occurrence[stack[-1]] > i:
                # Pop the character from stack and mark it as not seen.
                popped_char = stack.pop()
                seen.remove(popped_char)
            
            # Push the current character onto the stack and mark it as seen.
            stack.append(char)
            seen.add(char)
            
        return "".join(stack)

Remove Duplicate Letters in Java

class Solution {
    public String removeDuplicateLetters(String s) {
        // lastOccurrence[char] = index of last occurrence of char
        int[] lastOccurrence = new int[26];
        for (int i = 0; i < s.length(); i++) {
            lastOccurrence[s.charAt(i) - 'a'] = i;
        }

        // seen[char] = true if char is in our result stack
        boolean[] seen = new boolean[26];
        // Use a stack to build the lexicographically smallest subsequence
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            char currentChar = s.charAt(i);

            // If we have already included this character, skip it.
            if (seen[currentChar - 'a']) {
                continue;
            }

            // This is the greedy part.
            // If the current character is smaller than the character at the top of the stack,
            // and the top character will appear again later in the string,
            // we can pop the top character. This might lead to a lexicographically smaller result.
            while (!stack.isEmpty() && 
                   currentChar < stack.peek() && 
                   lastOccurrence[stack.peek() - 'a'] > i) {
                // Pop the character from stack and mark it as not seen.
                seen[stack.pop() - 'a'] = false;
            }

            // Push the current character onto the stack and mark it as seen.
            stack.push(currentChar);
            seen[currentChar - 'a'] = true;
        }

        // Build the result string from the stack
        StringBuilder sb = new StringBuilder();
        for (Character c : stack) {
            sb.append(c);
        }

        return sb.toString();
    }
}

Remove Duplicate Letters in C++

class Solution {
public:
    string removeDuplicateLetters(string s) {
        // last_occurrence[char] = index of last occurrence of char
        vector<int> last_occurrence(26, 0);
        for (int i = 0; i < s.length(); ++i) {
            last_occurrence[s[i] - 'a'] = i;
        }

        // seen[char] = true if char is in our result stack
        vector<bool> seen(26, false);
        string result_stack = "";

        for (int i = 0; i < s.length(); ++i) {
            char current_char = s[i];

            // If we have already included this character in an optimal position, skip it.
            if (seen[current_char - 'a']) {
                continue;
            }

            // This is the greedy part.
            // If the current character is smaller than the character at the top of the stack,
            // and the top character will appear again later in the string,
            // we can pop the top character. This might lead to a lexicographically smaller result.
            while (!result_stack.empty() && 
                   current_char < result_stack.back() && 
                   last_occurrence[result_stack.back() - 'a'] > i) {
                // Pop the character from stack and mark it as not seen.
                seen[result_stack.back() - 'a'] = false;
                result_stack.pop_back();
            }

            // Push the current character onto the stack and mark it as seen.
            result_stack.push_back(current_char);
            seen[current_char - 'a'] = true;
        }

        return result_stack;
    }
};

Remove Duplicate Letters in TypeScript

function removeDuplicateLetters(s: string): string {
    // lastOccurrence[char] = index of last occurrence of char
    const lastOccurrence: { [key: string]: number } = {};
    for (let i = 0; i < s.length; i++) {
        lastOccurrence[s[i]] = i;
    }

    const stack: string[] = [];
    const seen: Set<string> = new Set();

    for (let i = 0; i < s.length; i++) {
        const char = s[i];

        // If we have already included this character, skip it.
        if (seen.has(char)) {
            continue;
        }

        // This is the greedy part.
        // If the current character is smaller than the character at the top of the stack,
        // and the top character will appear again later in the string,
        // we can pop the top character. This might lead to a lexicographically smaller result.
        while (stack.length > 0 && 
               char < stack[stack.length - 1] && 
               lastOccurrence[stack[stack.length - 1]] > i) {
            // Pop the character from stack and mark it as not seen.
            const poppedChar = stack.pop()!;
            seen.delete(poppedChar);
        }

        // Push the current character onto the stack and mark it as seen.
        stack.push(char);
        seen.add(char);
    }

    return stack.join('');
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.