DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1 1

Remove Duplicate Letters

Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Example 1:

Input: s = "bcabc"
Output: "abc"

Example 2:

Input: s = "cbacdcbc"
Output: "acdb"

Constraints:

  • 1 <= s.length <= 104
  • s consists of lowercase English letters.

Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

SOLUTION:

class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        lastIndex = {}
        for i, c in enumerate(s):
            lastIndex[c] = i
        used = set()
        stack = []
        for i, c in enumerate(s):
            if c in used:
                continue
            while len(stack) > 0 and s[stack[-1]] > c and i < lastIndex[s[stack[-1]]]:
                curr = stack.pop()
                if s[curr] in used:
                    used.remove(s[curr])
            stack.append(i)
            used.add(c)
        return "".join(s[i] for i in stack)
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay