Skip to content

Commit ce1c22b

Browse files
committed
Time: 0 ms (100%), Space: 17.8 MB (58.63%) - LeetHub
1 parent c5d6267 commit ce1c22b

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# time complexity: O(n)
2+
# space complexity: O(n)
3+
class Solution:
4+
def smallestSubsequence(self, s: str) -> str:
5+
stack = []
6+
seen = set()
7+
lastCharIdx = {c: i for i, c in enumerate(s)}
8+
9+
for i, c in enumerate(s):
10+
if c not in seen:
11+
while stack and c < stack[-1] and i < lastCharIdx[stack[-1]]:
12+
seen.discard(stack.pop())
13+
seen.add(c)
14+
stack.append(c)
15+
16+
return ''.join(stack)
17+
18+
19+
s = "bcabc"
20+
print(Solution().smallestSubsequence(s))
21+
s = "cbacdcbc"
22+
print(Solution().smallestSubsequence(s))

0 commit comments

Comments
 (0)