<p>Given a string <code>s</code>, return <em>the </em><span data-keyword="lexicographically-smaller-string"><em>lexicographically smallest</em></span> <span data-keyword="subsequence-string"><em>subsequence</em></span><em> of</em> <code>s</code> <em>that contains all the distinct characters of</em> <code>s</code> <em>exactly once</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;bcabc&quot;
<strong>Output:</strong> &quot;abc&quot;
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;cbacdcbc&quot;
<strong>Output:</strong> &quot;acdb&quot;
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 1000</code></li>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>

<p>&nbsp;</p>
<strong>Note:</strong> This question is the same as 316: <a href="https://leetcode.com/problems/remove-duplicate-letters/" target="_blank">https://leetcode.com/problems/remove-duplicate-letters/</a>
class Solution:
    def smallestSubsequence(self, s: str) -> str:
        def isoccuringlast(i:int,l:str,s:str):
            flag = False
            while i < len(s):
                if s[i] == l:
                    flag = True
                i += 1
            return flag

        def f(s:str, arr:list, stack:list):
            for i in range(len(s)):
                # print(stack)
                if arr[ord(s[i]) - 97] == 0:
                    if len(stack) == 0:
                        stack.append(s[i])
                        arr[ord(s[i]) - 97] = 1
                    else:
                        curr = stack[-1]
                        if s[i] > curr:
                            stack.append(s[i])
                            arr[ord(s[i]) - 97] = 1
                        else:
                            while len(stack) > 0 and s[i] < curr:
                                # print(stack,curr)
                                occuredornot = isoccuringlast(i , curr , s)
                                if occuredornot:
                                    stack.pop()
                                    arr[ord(curr) - 97] = 0
                                    if len(stack) > 0:
                                        curr = stack[-1]
                                else:
                                    break
                            stack.append(s[i])
                            arr[ord(s[i]) - 97] = 1
        arr = []
        for i in range(26):
            arr.append(0)
        stack = []
        f(s , arr , stack)
        # print(stack)
        return "".join(stack)
16400