Search⌘ K
AI Features

Solution: Remove Duplicate Letters

Understand how to implement a greedy algorithm using a stack to remove duplicate letters from a string and generate the lexicographically smallest result. Learn to track character frequency, manage visited characters, and optimize the string output with O(n) time complexity.

Statement

You are given a string, s, consisting only of lowercase English letters. Your task is to remove duplicate letters so that:

  1. Each letter appears only once in the resulting string.

  2. The resulting string is the smallest in lexicographical order among all possible results that satisfy the above condition.

Return the final string.

A string, a, is considered lexicographically smaller than string b if:

  • In the first position where they differ, the character in a appears earlier in the alphabet than in b.

  • If a is a ...