You are given a string s that consists of lowercase English letters.
You can perform the following operation any number of times (possibly zero times):
s and delete any one occurrence.Return the lexicographically smallest resulting string that can be formed this way.
Example 1:
Input: s = "aaccb"
Output: "aacb"
Explanation:
We can form the strings "acb", "aacb", "accb", and "aaccb". "aacb" is the lexicographically smallest one.
For example, we can obtain "aacb" by choosing 'c' and deleting its first occurrence.
Example 2:
Input: s = "z"
Output: "z"
Explanation:
We cannot perform any operations. The only string we can form is "z".
Constraints:
1 <= s.length <= 105s contains lowercase English letters only.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
This search deletes one extra copy of a letter at a time and remembers every string it can reach. A deletion is allowed only while that letter still appears at least twice. The smallest string visited is the answer, and the search grows quickly because each string branches into many shorter ones.
Here's how the algorithm would work step-by-step:
def lexicographically_smallest_string(text):
# Every reachable string comes from deleting one extra copy at a time.
best_string = text
seen_strings = {text}
pending_strings = [text]
while pending_strings:
current_string = pending_strings.pop()
letter_counts = {}
for character in current_string:
letter_counts[character] = letter_counts.get(character, 0) + 1
for index, character in enumerate(current_string):
if letter_counts[character] < 2:
continue
# This copy can go because the letter still appears somewhere else.
candidate = current_string[:index] + current_string[index + 1 :]
if candidate in seen_strings:
continue
seen_strings.add(candidate)
if candidate < best_string:
best_string = candidate
pending_strings.append(candidate)
return best_string
Every letter that appears in the input has to stay at least once, and an extra copy can be deleted while another copy remains. The scan keeps a stack and drops a larger letter when a smaller letter arrives and a spare copy of the larger letter still exists. Leftover copies at the end are removed when they cannot make the result smaller.
Here's how the algorithm would work step-by-step:
def lexicographically_smallest_string(text):
# Spare copies are what make a deletion legal, so count every letter first.
letter_counts = {}
for character in text:
letter_counts[character] = letter_counts.get(character, 0) + 1
kept_characters = []
for character in text:
# Drop a larger letter when a smaller one arrives and a spare copy remains.
while (
kept_characters
and kept_characters[-1] > character
and letter_counts[kept_characters[-1]] > 1
):
removed_character = kept_characters.pop()
letter_counts[removed_character] -= 1
kept_characters.append(character)
# Copies left on the end cannot help, so trim them while a spare remains.
while kept_characters and letter_counts[kept_characters[-1]] > 1:
removed_character = kept_characters.pop()
letter_counts[removed_character] -= 1
return "".join(kept_characters)
| Case | How to Handle |
|---|---|
| Empty string or single character string | Return the input string directly as no duplicates can exist or need removal. |
| String with all identical characters | Greedy stack approach keeps only the last occurrence of the character to ensure minimal length and valid order. |
| String already in strictly increasing lexicographical order | The algorithm processes the characters and returns the original string without unnecessary removals. |
| String in strictly decreasing lexicographical order with duplicates | Frequency tracking and stack pops remove earlier larger characters, retaining only the final instance of each character. |
| Maximum length constraints up to the problem limit | Using a linear time stack and frequency array approach ensures optimal O(N) time and space complexity without scaling issues. |
| Characters with alternating frequencies and values | Monotonic stack checks character availability using a remaining frequency map to safely pop larger elements when smaller ones can appear later. |
| String containing special characters or mixed cases | Standard ASCII values dictate lexicographical comparisons natively, allowing the same logic to apply without modification. |
| Duplicate characters scattered far apart | A frequency count array tracks remaining occurrences globally so earlier characters are only popped if more are guaranteed to follow. |