You are given a string s of lowercase letters. Delete letters so that every distinct letter of s is left exactly once, without changing the order of the letters you keep.
Many such results may exist. Return the one that comes first in dictionary order.
Example 1
Input: s = "cdadbc" Output: "adbc" Why: a can lead, but the only d after it is before b
2 more examples and the constraints
Example 2
Input: s = "bab" Output: "ab" Why: drop the first b; the last b still follows a
Example 3
Input: s = "zyx" Output: "zyx" Why: every letter appears once, so nothing can move
Constraints
- 1 ≤ s.length ≤ 10,000
scontains only the letters a to z
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Pick one letter per roundO(26 · n)
- Monotonic stackO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 10,000 | Verdict |
|---|---|---|---|
| Pick one letter per round | O(26 · n) | Passes; easy to prove | |
| Monotonic stack | O(n) | Best; one pass |
n = length of s. The alphabet has 26 letters.
Edge cases to test
- One letter. "q" returns "q".
- No repeats. "zyx" cannot change, even though it is not sorted.
- One letter repeated. "aaaa" returns "a"; later copies are skipped because a is already on the stack.
- Last copy on top. In "cdadbc", d at index 3 must stay even though b is smaller.
Common mistakes
- Popping a bigger letter that never appears again, which loses it from the answer.
- Not skipping letters already on the stack, which lets a letter appear twice.
- Sorting the distinct letters, which ignores the order rule ("zyx" is not "xyz").
How to talk through it
- 1Clarify. Must the kept letters stay in their original order? Only lowercase letters?
- 2Find the rule. A bigger letter before a smaller one is worth removing, but only if it appears again later.
- 3Use a stack. Pop while the top is bigger and returns later, then push; skip letters already used.
- 4Give the cost. Each letter is pushed and popped once: O(n) time, O(26) space.
- 5Test out loud. Run "bab", "zyx" and "cdadbc" through the loop.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?