Remove Duplicate Letters
Given a string of lowercase letters, remove duplicate letters so each appears exactly once. The result must be the smallest lexicographical result possible while preserving the relative order of first occurrences of each letter.
A monotonic increasing stack with a frequency counter solves this. Count frequencies. Iterate, decrement count for each char. If already used, skip. While the stack top is greater than the current char and the top char appears later, pop the top (mark as unused). Push current char, mark as used. This greedy approach ensures the smallest lexicographical result.
Example Input & Output
No duplicates.
Smallest lexicographical.
Lexicographically smallest.
Algorithm Flow

Solution Approach
Count frequencies. Iterate, decrement. Skip if used. While stack top > char and top appears later, pop. Push char.
Time O(n), Space O(n).
Best Answers
import java.util.*;
class Solution {
public String solution(String s) {
int[] cnt = new int[26];
boolean[] used = new boolean[26];
Stack<Character> stack = new Stack<>();
for (char ch : s.toCharArray()) cnt[ch - 'a']++;
for (char ch : s.toCharArray()) {
cnt[ch - 'a']--;
if (used[ch - 'a']) continue;
while (!stack.isEmpty() && ch < stack.peek() && cnt[stack.peek() - 'a'] > 0)
used[stack.pop() - 'a'] = false;
stack.push(ch);
used[ch - 'a'] = true;
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) sb.insert(0, stack.pop());
return sb.toString();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
