Leetcode Problem 316. Remove Duplicate Letters

316. Remove Duplicate Letters

Leetcode Solutions

Greedy Approach with Stack

  1. Initialize a stack to keep the characters that form the result string.
  2. Use a hash set to keep track of the characters that are already in the stack.
  3. Use a hash map to count the occurrences of each character in the string.
  4. Iterate over the characters of the string. a. Decrement the count of the current character in the hash map. b. If the current character is not in the hash set: i. While the stack is not empty, the current character is less than the top character of the stack, and the top character of the stack has more occurrences in the future, pop the stack and remove the popped character from the hash set. ii. Push the current character onto the stack and add it to the hash set.
  5. Convert the stack into a string and return it.
UML Thumbnail

Recursive Greedy Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...