316. Remove Duplicate Letters

Description

Given a string s, 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.

Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

Constraints

  • 1 <= s.length <= 104

  • s consists of lowercase English letters.

Approach

  • GeeksforGeeks

  • ProgramCreek

  • YouTube

Examples

Input: s = "bcabc"

Output: "abc"

Solutions

/**
 * Time complexity : 
 * Space complexity : 
 */

class Solution {
    public String removeDuplicateLetters(String s) {
        if(s == null || s.length() == 0) return "";
        
        int[] count = new int[128];
        char[] result = new char[26];
        boolean[] assigned = new boolean[128];
        
        int sLen = s.length();
        
        for(int i = 0; i < sLen; i++) {
            count[s.charAt(i)]++;
        }
        
        char ch;
        int end = -1;
        
        for(int i = 0; i < sLen; i++) {
            ch = s.charAt(i);
            count[ch]--;
            
            if(assigned[ch]) continue;
            
            while(end >= 0 && result[end] > ch && count[result[end]] > 0) {
                assigned[result[end]] = false;
                end--;
            }
            
            end++;
            result[end] = ch;
            assigned[ch] = true;
        }
        
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i <= end; i++) {
            sb.append(result[i]);
        }
        
        return sb.toString();
    }
}

Follow up

Last updated

Was this helpful?