AlgoMaster Logo

Remove Duplicate Letters

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Greedy approach with Stack and HashMap

Intuition:

The task is to remove duplicate letters and return the lexicographically smallest result. To achieve this, we need to ensure that for each character, we decide whether to keep it or remove it based on its placement and frequency.

Steps:

  1. Use a HashMap to record the last occurrence of each character in the string. This helps us determine if a character can be safely removed when traversing the string.
  2. Use a Stack to build the result string.
  3. Use a boolean array to keep track of characters in the current stack to prevent duplicates.
  4. Traverse each character in the string:
    • If the character is already in the stack, skip it.
    • Otherwise, compare it with the top of the stack, and if the top character appears later, and the current character is smaller, pop the stack.
    • Push the current character onto the stack and mark it in the boolean array.
  5. Convert the stack into the resulting string.

Code:

2. Optimized Greedy with Char Array as Stack

Intuition:

Instead of using a stack data structure, we can use a character array to simulate stack behavior. This slight optimization can lead to performance improvements by reducing method call overheads of Stack operations.

Steps:

  1. Follow similar logic to the stack-based approach, managing character presence using an array.
  2. Use a char[] array to act as a stack, managing a pointer to simulate stack-like push/pop operations.

Code: