316. Remove Duplicate Letters
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example 1:
Example 2:
Thoughts
Greedy: In the search space of i to j where the last character in s[i...j] in also of its last appearance of the whole string s, find the small character in lexicographical order, delete it in the subsequent substring and then perform the search starting from j + 1.
Using stack:
Count the letter frequency with an Array
Build a ascending stack: Each time adding a letter to the stack if it has not been added into the stack, mark letter as visited. If current letter is smaller than the that on top of the stack, and top letter has remaining appearance after (as checked by indexing the letter frequency array), pop the letter out and mark it as not visited
Code 1: O(n)
Code 2 : O(n)
Last updated
Was this helpful?