Skip to content

Commit 55724fd

Browse files
committed
O(n) time and O(1) space using Hashset and Hashtable Greedy Approach
1 parent 5f6479d commit 55724fd

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""
2+
Given a string which contains only lowercase letters, 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.
3+
4+
Example 1:
5+
6+
Input: "bcabc"
7+
Output: "abc"
8+
Example 2:
9+
10+
Input: "cbacdcbc"
11+
Output: "acdb"
12+
"""
13+
class Solution:
14+
def removeDuplicateLetters(self, s: str) -> str:
15+
stack = []
16+
seen = set()
17+
last_index = {char:i for i,char in enumerate(s)}
18+
for i,char in enumerate(s):
19+
if char not in seen:
20+
"""
21+
Need to first see if the char is already seen or not. If seen no need to bother otherwise we'll check.
22+
"""
23+
while stack and char < stack[-1] and i < last_index[stack[-1]]:
24+
seen.discard(stack.pop())
25+
seen.add(char)
26+
stack.append(char)
27+
return ''.join(stack)

0 commit comments

Comments
 (0)