Leetcode 316. Remove Duplicate Letters
The task is to remove duplicate letters from a given string s
so that every letter appears only once, and we must make sure our result is the smallest in lexicographical order among all possible results.
Example:
Input: s = "bcabc"
Output: "abc"
Input: s = "cbacdcbc"
Output: "acdb"
s
will consist of lowercase English letters only.s
will be at least 1 and at most 1000.To solve this problem, we can use a greedy approach with a stack data structure to build the resultant string:
import java.util.*;
public class Solution {
public String removeDuplicateLetters(String s) {
int[] freq = new int[26]; // Frequency of each character
boolean[] visited = new boolean[26]; // Whether the character is in stack or not
// Calculate the frequency of each character
for (char c : s.toCharArray()) {
freq[c - 'a']++;
}
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
freq[c - 'a']--; // Decrease frequency each time we encounter the character
// If char is already in stack, continue
if (visited[c - 'a']) continue;
// Remove characters from the stack to maintain lexicographical order
while (!stack.isEmpty() && stack.peek() > c && freq[stack.peek() - 'a'] > 0) {
visited[stack.pop() - 'a'] = false;
}
stack.push(c);
visited[c - 'a'] = true;
}
// Build the resultant string from the stack
StringBuilder result = new StringBuilder();
for (char c : stack) {
result.append(c);
}
return result.toString();
}
}
s
.Overall, the time complexity is O(n), making this approach efficient for the problem constraints.
The space complexity is O(1) if we only consider the additional data structures used (frequency array, visited array, and stack), since the total auxiliary space used is constant concerning the alphabet size (26). However, taking into account the stack and result, it is O(n), where n is the length of the input string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?