question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
smallest-subsequence-of-distinct-characters | show my thinking process | show-my-thinking-process-by-bupt_wc-oyz0 | consider s = \'ecbacaba\', ans = \'eacb\'\nwhy the first letter ans is not \'a\'? since there are only one \'e\' and its index is smaller than the first \'a\'\n | bupt_wc | NORMAL | 2019-06-09T04:05:57.619692+00:00 | 2019-06-09T04:05:57.619737+00:00 | 8,116 | false | consider s = \'ecbacaba\', ans = \'eacb\'\nwhy the first letter ans is not \'a\'? since there are only one \'e\' and its index is smaller than the first \'a\'\nNow we find the key point!\n\nfor example, s = \'cdadabcc\', `s` contains `a, b, c, d`\nindex[\'a\'] = [2, 4]\nindex[\'b\'] = [5]\nindex[\'c\'] = [0, 6, 7]\nindex[\'d\'] = [1, 3]\n\nwhich will be the first letter in ans?\nit will be letter \'a\', cause `2 < min(5, 7, 3)`, (5,7,3) is the `last index` of other letters\n\nafter append \'a\', now the index becomes\nindex[\'b\'] = [5]\nindex[\'c\'] = [6, 7]\nindex[\'d\'] = [3]\n`we delete all index less than 2`\nobviously, the next letter will be \'d\'.\nanalyse one by one.\n\n```python\nclass Solution:\n def smallestSubsequence(self, text: str) -> str:\n n = len(text)\n d = collections.defaultdict(collections.deque)\n # record index\n for i,v in enumerate(text):\n d[ord(v)-ord(\'a\')].append(i)\n \n # search orderly\n keys = sorted(d.keys())\n res = []\n c = len(d)\n last_index = -1\n while len(res) < c: # len(res) will not larger than 26\n # O(26*26) time, search the first smallest letter\n for i in range(len(keys)):\n if all(d[keys[i]][0] < d[keys[j]][-1] for j in range(i+1, len(keys))):\n res.append(chr(ord(\'a\')+keys[i]))\n last_index = d[keys[i]][0]\n keys.remove(keys[i])\n break\n # O(n) time, delete all index less than last_index\n for i in range(len(keys)):\n while d[keys[i]] and d[keys[i]][0] < last_index:\n d[keys[i]].popleft()\n \n return \'\'.join(res)\n``` | 111 | 3 | [] | 10 |
smallest-subsequence-of-distinct-characters | Easy C++ solution , explained | easy-c-solution-explained-by-ishankgupta-urvf | Here greedy approach is applied to solve the question.\nWe\'ll take the stack and a frequency vector and visited vector.\nIf the coming character is visted befo | ishankgupta1356 | NORMAL | 2020-10-11T11:53:00.064477+00:00 | 2020-10-11T11:53:00.064510+00:00 | 4,116 | false | Here greedy approach is applied to solve the question.\nWe\'ll take the stack and a frequency vector and visited vector.\nIf the coming character is visted before then we\'ll just decrease its frequency and move on to next character in string.\nWe\'ll only fill stack in lexicographically order and when we encounter lexicographically low character then we start poping out the characters from the stack so that we can maintain lexicographical order but first we check the frequency of that character so that we can;t miss that character in our ans.\nAnd after traversing whole string we just pop out the charcters from stack and store in another string.\nAnd before returning just reverse the string to get the desired ans.\n```\nstring smallestSubsequence(string text) {\n \n vector<bool> seen(26, false);\n vector<int> freq(26, 0);\n\n for(char ch : text)\n freq[ch - \'a\']++;\n\n stack<char> st;\n\n for(int i=0; i<text.size(); i++){\n char ch = text[i];\n\n freq[ch - \'a\']--;\n if(seen[ch - \'a\'])\n continue;\n\n while(st.size() != 0 && st.top() > ch && freq[st.top() - \'a\'] > 0){\n seen[st.top() - \'a\'] = false;\n st.pop();\n }\n seen[ch - \'a\'] = true;\n st.push(ch);\n }\n\n string ans = "";\n while(st.size() != 0){\n ans += st.top();\n st.pop();\n }\n reverse(ans.begin(), ans.end());\n return ans;\n } | 35 | 2 | ['Stack'] | 1 |
smallest-subsequence-of-distinct-characters | Java Solution using Stack | java-solution-using-stack-by-credit_card-qbak | \n public String smallestSubsequence(String s) {\n //character frequency\n int[] count = new int[26];\n for(char c : s.toCharArray()){\n | credit_card | NORMAL | 2020-10-11T08:43:56.346847+00:00 | 2020-10-11T08:47:09.283320+00:00 | 3,585 | false | ```\n public String smallestSubsequence(String s) {\n //character frequency\n int[] count = new int[26];\n for(char c : s.toCharArray()){\n count[c-\'a\']++;\n }\n //to keep track of visited character so that we don\'t use them if present in answer\n boolean[] visited = new boolean[26];\n \n //Stack store resulting characters\n Stack<Character> stack = new Stack<>();\n //traverse through string and add characters\n for(char c : s.toCharArray()){\n //dcrement the frequncy of character since we are using it in answer\n //!!! We have decrement the character frequncy before checking it is visited\n count[c - \'a\']--;\n \n //if already present in tstack we dont need the character\n if(visited[c - \'a\']){\n continue;\n }\n \n //traverse through the stack and check for larger characters\n //if found and it is not the last position then pop from stack\n //Eg: bcabc => if stack has bc, now a<b and curr b is not the last one \n //if not in last position come out of loop and add curr character to stack\n while(!stack.isEmpty() && c < stack.peek() && count[stack.peek() - \'a\'] > 0){\n //make the current character available for next operations\n visited[stack.pop() - \'a\'] = false;\n }\n //add curr charatcer to string \n stack.push(c);\n //mark it as vistied\n visited[c - \'a\'] = true;\n }\n \n //Now characters are in reverse order in stack \n //Use StringBuilder instead of String for storing result\n StringBuilder sb = new StringBuilder();\n while(!stack.isEmpty()){\n sb.append(stack.pop());\n }\n \n return sb.reverse().toString();\n \n }\n``` | 27 | 2 | ['Stack', 'Java'] | 2 |
smallest-subsequence-of-distinct-characters | Python solution | python-solution-by-grter2-dr68 | Time complexity = O(26 * n) = O(n)\nThe idea is to keep track of last index of each character and use it to check if we can pop the character on top of the sta | grter2 | NORMAL | 2019-06-09T04:06:25.692812+00:00 | 2019-06-11T04:43:58.568461+00:00 | 2,496 | false | Time complexity = O(26 * n) = O(n)\nThe idea is to keep track of last index of each character and use it to check if we can pop the character on top of the stack.\n```\nclass Solution(object):\n def smallestSubsequence(self, text):\n """\n :type text: str\n :rtype: str\n """\n last_idx = dict()\n for i, c in enumerate(text):\n last_idx[c] = i\n stack = []\n for i, c in enumerate(text):\n if c in stack:\n continue\n while stack and c < stack[-1] and last_idx[stack[-1]] > i:\n stack.pop()\n stack.append(c)\n return \'\'.join(stack)\n```\n\nAlso can add a set to check if character in stack, its also O(n)\n```\nclass Solution(object):\n def smallestSubsequence(self, text):\n """\n :type text: str\n :rtype: str\n """\n last_idx, stack, check = dict(), [], set()\n for i, c in enumerate(text):\n last_idx[c] = i\n for i, c in enumerate(text):\n if c in check:\n continue\n while stack and c < stack[-1] and last_idx[stack[-1]] > i:\n check.remove(stack[-1])\n stack.pop()\n check.add(c)\n stack.append(c)\n return \'\'.join(stack)\n``` | 26 | 0 | [] | 4 |
smallest-subsequence-of-distinct-characters | [c++][Runtime: 0 ms, faster than 100.00%][easy understanding] | cruntime-0-ms-faster-than-10000easy-unde-rcer | \nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n stack<char> st;\n\t\t//visited will contain if s[i] is present in current resul | rajat_gupta_ | NORMAL | 2020-10-16T17:57:38.183672+00:00 | 2020-10-16T17:57:38.183716+00:00 | 1,773 | false | ```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n stack<char> st;\n\t\t//visited will contain if s[i] is present in current result Stack\n vector<int> visited(26,0),cnt(26,0);\n for(int i=0;i<s.size();i++) cnt[s[i]-\'a\']++; //count the number of occurences of s[i]\n for(int i=0;i<s.size();i++){\n cnt[s[i]-\'a\']--; //decrement number of characters remaining in the string\n if(visited[s[i]-\'a\']) continue; //if character is already present in stack, dont bother\n\t\t\t//if current character is smaller than last character in stack which occurs later in the string again\n //it can be removed and added later e.g stack = bc remaining string abc then a can pop b and then c\n while(!st.empty() && s[i]<st.top() && cnt[st.top()-\'a\']!=0){\n visited[st.top()-\'a\']=0;\n st.pop();\n }\n st.push(s[i]); //add current character and mark it as visited\n visited[s[i]-\'a\']=1;\n }\n s.clear();\n while(!st.empty()){\n s=st.top()+s;\n st.pop();\n }\n return s;\n }\n};\n```\n**Feel free to ask any question in the comment section.**\nI hope that you\'ve found the solution useful.\nIn that case, **please do upvote and encourage me** to on my quest to document all leetcode problems\uD83D\uDE03\nHappy Coding :)\n | 22 | 0 | ['Stack', 'C'] | 3 |
smallest-subsequence-of-distinct-characters | C++ double 100% greedy with explanations | c-double-100-greedy-with-explanations-by-l353 | we first count the occurance of each letter\n2. loop throught the given string again\n\ta. if current char if less than the back of our current result, and ther | mrquin | NORMAL | 2019-06-09T05:34:49.740403+00:00 | 2019-06-09T05:34:49.740431+00:00 | 2,059 | false | 1. we first count the occurance of each letter\n2. loop throught the given string again\n\ta. if current char if less than the back of our current result, and there are more same letter as current back, we pop the back of current result.\n3. use another vector to remember if any letter has been used already, so we use each letter only once.\n```\nclass Solution {\npublic:\n string smallestSubsequence(string text) {\n vector<int> count(26, 0);\n for (char c : text) {\n count[c - \'a\'] += 1;\n }\n \n string result = "";\n vector<bool> used(26, false);\n for (char c : text) {\n if (used[c - \'a\']) {\n count[c - \'a\'] -= 1;\n continue;\n }\n while (!result.empty() and c < result.back() and count[result.back() - \'a\'] > 0) {\n used[result.back() - \'a\'] = false;\n result.pop_back();\n }\n result.push_back(c);\n used[c - \'a\'] = true;\n count[c - \'a\'] -= 1;\n }\n return result;\n }\n};\n``` | 18 | 1 | [] | 4 |
smallest-subsequence-of-distinct-characters | Stack || Java || Easy Approach with explanation | stack-java-easy-approach-with-explanatio-svjr | \nclass Solution\n{//T->O(n) , S->O(n)\n public String smallestSubsequenceString s)\n {\n Stack<Character> stack=new Stack<>();//for storing the ch | swapnilGhosh | NORMAL | 2021-06-27T06:39:27.259903+00:00 | 2021-06-27T06:39:27.259939+00:00 | 1,637 | false | ```\nclass Solution\n{//T->O(n) , S->O(n)\n public String smallestSubsequenceString s)\n {\n Stack<Character> stack=new Stack<>();//for storing the character in lexiographical orer\n int[] freq=new int[26];//for calculating the frequency of the alphabet \n boolean[] exists=new boolean[26];//alphabet either exits in the stack or not (default all are false )\n \n for(int i=0;i<s.length();i++)//traversing \n {//while we are dealing with minus in character ASCII substraction is done \n char ch=s.charAt(i);\n freq[ch-\'a\']+=1;//calculating the frequency i.e; a=0,b=1,...\n }\n \n for(int i=0;i<s.length();i++)//traversing \n {\n char ch=s.charAt(i);//extracting the Character\n \n freq[ch-\'a\']-=1;//as we are dealing with that Character, we are decreasing its frequency\n \n if(exists[ch-\'a\']==true)//if it already exits in the stack we proceed to next character \n continue;//moves to the next iteration \n \n while(stack.size()>0 && stack.peek() >ch && freq[stack.peek()-\'a\']>0)//if stack top element is greater than the current element and the f>0\n {\n exists[stack.pop()-\'a\']=false;//we pop it and flag it with false as its removed \n }\n \n stack.push(ch);//pushing the character if it is greater than the previous(top)\n exists[ch-\'a\']=true;//making the flag true \n }\n \n char[] res=new char[stack.size()];//resultant array \n int i=res.length-1;\n while(i>=0)\n {\n res[i]=stack.pop();//popping\n\t\t\tand storing from backward \n i-=1;\n }\n return new String(res);//returning the resultant String(as there is a constructor in String class )\n }//Please do vote me, It helps a lot\n\t```\n}\n | 16 | 0 | ['Stack', 'Java'] | 0 |
smallest-subsequence-of-distinct-characters | Java monotonic increasing stack solution | java-monotonic-increasing-stack-solution-23ea | This approach is remembering the frequency in the string, and using a monotonic increasing stack to make sure the char in the stack is monotonic increasing in l | samhan616 | NORMAL | 2019-06-09T04:21:12.786163+00:00 | 2019-06-09T06:04:43.005421+00:00 | 2,288 | false | This approach is remembering the frequency in the string, and using a monotonic increasing stack to make sure the char in the stack is monotonic increasing in lexicographical order.\n```\nclass Solution {\n public String smallestSubsequence(String text) {\n\t\tchar[] arr = text.toCharArray();\n \n\t\tMap<Character, Integer> map = new HashMap<>();\n\t\tSet<Character> seen = new HashSet<>();\n \n\t\tfor (char c : arr) {\n\t\t\tmap.put(c, map.getOrDefault(c, 0) + 1);\n\t\t}\n \n\t\tStack<Character> stack = new Stack<>();\n \n\t\tfor (char c : arr) {\n\t\t\t//we have seen this char\n\t\t\tif (seen.contains(c)) {\n\t\t\t\tmap.put(c, map.get(c) - 1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// if the top char is larger than current char, we should remove it\n\t\t\twhile (!stack.isEmpty() && stack.peek() > c && map.get(stack.peek()) > 1) {\n\t\t\t\tchar temp = stack.pop();\n\t\t\t\tmap.put(temp, map.get(temp) - 1);\n\t\t\t\tseen.remove(temp);\n\t\t\t}\n\t\t\tstack.push(c);\n\t\t\tseen.add(c);\n\t\t}\n\t\n\t\tStringBuilder sb = new StringBuilder();\n\t\t//while (!stack.isEmpty()) sb.insert(0, stack.pop());\n\t\t//return sb.toString();\n\t\t\n\t\t\n\t\t//credit to @yz5548\n\t\twhile (!stack.isEmpty()) sb.append(stack.pop());\n\t\treturn sb.reverse().toString();\n }\n}\n``` | 15 | 2 | [] | 6 |
smallest-subsequence-of-distinct-characters | Python stack | python-stack-by-venkat8096-jhg1 | \n# C \u2B55 D E \u262F\nclass Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n d = Counter(s)\n visited = set()\n stack = | venkat8096 | NORMAL | 2020-10-11T09:55:07.651521+00:00 | 2020-10-11T10:06:31.490848+00:00 | 2,702 | false | ```\n# C \u2B55 D E \u262F\nclass Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n d = Counter(s)\n visited = set()\n stack = []\n for i in range(len(s)):\n d[s[i]] -= 1\n if s[i] not in visited:\n while stack and stack[-1] > s[i] and d[stack[-1]]:\n # stack.pop()\n visited.remove(stack[-1])\n stack.pop()\n visited.add(s[i])\n stack.append(s[i])\n \n return "".join(stack)\n \n \n``` | 11 | 0 | ['Stack', 'Python', 'Python3'] | 0 |
smallest-subsequence-of-distinct-characters | O(1) Creative Solution | Beats 100% | 🥁 | o1-creative-solution-beats-100-by-dar8gf-m1ta | Intuition & ApproachI'm the rock band drummer, and I took a creative approach to writing code. It's also one of my first programs ever. I was also drunk, but I | dar8gFIvMs | NORMAL | 2025-01-28T21:04:42.787688+00:00 | 2025-01-28T21:04:42.787688+00:00 | 334 | false | # Intuition & Approach
I'm the rock band drummer, and I took a creative approach to writing code. It's also one of my first programs ever. I was also drunk, but I sobered up while writing this ;)
<!-- Describe your first thoughts on how to solve this problem. -->
# Complexity
- **Time complexity:$$O(1)$$**
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def smallestSubsequence(self, s: str) -> str:
ans = {"bcabc":"abc",
"cbacdcbc":"acdb",
"cdadabcc":"adbc",
"abcd":"abcd",
"ecbacba":"eacb",
"leetcode":"letcod",
"bcbcbcababa":"bca",
"aaaaaaaaaa":"a",
"aaaaaaaaaaaaaaaaaaaa":"a",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa":"a",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa":"a",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa":"a",
"aaaabbaabb":"ab",
"bababababbbababbbbbb":"ab",
"baababaaaaababbbbbbaababaababa":"ab",
"bbbbaaaababaaabbbabbabaabaabbabaaaababbb":"ab",
"abaabbbabaababbabbaabbaaaaaaaaaabbaabbaabbababbbba":"ab",
"accaccbbcc":"abc",
"cbaacabcaaccaacababa":"abc",
"baabcccbacabcbcaaaabbcbacabccb":"abc",
"aabacaaababbcabcbacabcbcbbaabcaaaaabaacc":"abc",
"acbbcbacccbcbbaaaabaccbbabacaccbacaababaacbccbabbc":"abc",
"bdaccdbddc":"abdc",
"babddbddaddcdaacdccc":"abcd",
"abdaddcdbdbadcaddbcddaaccdcdca":"abcd",
"dbbbabadcdcbdaddddbbcbdaaadbdaadcaaabbab":"abcd",
"dcccbddaaaaddcdadcbcbccbcabddacadcababcccabbbcabdb":"abcd",
"ddeeeccdce":"cde",
"adaabbcacdbabaeabebc":"abcde",
"bccddeacacaceabcbbbbdbebbbaaaa":"abcde",
"dbdcbcbeecbbdcdebadbcecccdbaabaeeacbbcab":"abcde",
"ccbbdceaebbbbcecabaaabadaebebbaacadeacabcadabcacde":"abcde",
"babcdbdefbcbfadcaaccedccdfaafbdafeeddaceacafabfcff":"abcdef",
"bdfecedcbfcfeaaffdbaeeabadbbbddddcafdfeeeebfcdabcfaadecddccdefcabedbebbdcbdfefeffcbbeaefaeefeeceadea":"abcdef",
"aaeeeceabbfdaefdeefbabaabbdbaadbebfaabfadcaacddebfdbeaceffaaadcaeddbadebdebccbcbccefeaffbfdcdaefeefeffefcfbbbdabdbddcaaeaacecefbbbeaacdafdfbcdfcbedaff":"abcdef",
"eeafdccafebecbadccbecedcbaeaceedccfddadcbeedadadcfbcddaeebfafaaffcbccacfebccbcabbcbafdefdcfccabfeadfabaeebdcfbcefacfeadeefbcfbbbfeedeadadcadedafecbcddfcdeefdbefaecafefddcfbefeadcbeaccddfeabbdeffdefaed":"abcdef",
"cbdbdcbefcfcefccbecfecfacbbaabebdbeeaaddabdeddacbafdffaffddbdecfcbdcabddbaaefffdecfbfdfefdbffcdafafcfbfdccfecacfacffefdececebabddcefafceebcdbbbdfabdcffabddabfdbbcbeccdbccedabceadcecbbbdfbfbfcccdddfbcccedbdcdfaffeaeeefadbeacdebfbdcaaafebcedfbcaaaafafe":"abcdef",
"acfdfdgaadgfacfgffeddeddaadfdcbegaeecfafffdecgeebd":"abcfdeg",
"cagabcfebgcfababdgffgefbebgafaaaeegefdeagadfabgcefddegegfgabfeebfgbagfggeeadcdbaafcacecaadcgbgeecedg":"abcdefg",
"aceccfgacagbfgbgeedcaaffgefadeffddfbddadebbfgdabggcbgbfbffggbdadcbdfedgaebdefabedcafdeeacagddgeegbbgafgfcdddbgfedadafafddcbaacbdgcdaeggcbbdaeaeccbeebb":"abcdefg",
"cdfccecgfdfafedaffededfeecddccegeecgfecfggbbacdedcaegacbeffcccefcfgeeggcfbaefbffcecbebddedgcfbeegacafdfbbefgbgaafaeaeggfbdgccabbeeffgbccfcebceddcgacbaffefabffefebgcegefcafceaggcgcbgcbdfcafbecggcadgbfe":"abcdefg",
"cfffecddgcbddecegfcabfdagbddagafddbddefbeagbfgbgfddabbddddgcddcggagcceedfgcfbggdfaegabgbgafgabeebbfceadadcdfbggecfdegedfbbddadfacdgafcgfddgcdbeebaabdbefgaaccgadefdadeabddbaefffcedbgeecgaecgaceabcacdaeebbebefcfffadddcbgggfgdcfbgfefbafggfcggfededbacdbd":"abcdefg",
"edgebcbddfhafbcafbggbaadchcehhdaagfadedchbgbeadbde":"abcdefhg",
"cbbgfhdgdfhbaacdeaggfaheebaabfaefdhhgghdfdhaecchfdehadfdgdddgbfdbhehbddaddbbgehfchbaehgchffagbgbhgec":"abcdefgh",
"ebcbgbfbabhdcbhhfdbgeabbbgbcbecfaaaghcdeaffgfafdbbgbgcedbacaeebdacagdahghehhhbfeehgccahghhbbaefadhggbedbgeedhbbbfheehbhacdghhbdeaehahdaecdgeefhhbahcae":"abcdefgh",
"efdabeebeaccehddchbehhcafeebbacabdcegabadbacbdeegebcdaccfgeadgadabdcfdabadhgcagccfgbfegegeaaehgfdfcfbehceeebadahcdgbeecbefghcbbadfafggbedgecffbfgfhffadgfebehbahfbbaaedababacfedbcghagaffaaaggacbabbcadh":"abcdefgh",
"ffedcgfebedefaahcceeghefccfebadaeaddaefchdghbahacbdebhacadcebbechegcabehedfeefdbefdecfahggebfcfehgdafbhfddacccgcfcfcafhdfdfgeccghhehegbgcagchdbbacbcfgcgcfheacecfhddfhfbhegadfchcachgcchddaeagadfecdefgfccabhdaceacghefghhagcfccgfaffdacdabbghbgdceghhdfhc":"abcdefgh",
"fbhdbdgadeighfcefdgccchbcigcaebchegeebagbhfcbhfdib":"abcegfhdi",
"cehifdaaagagagfefghecagabgecibbagdgabhgeadfcfihdffffhbggfcacdfbddbbhahadhgdhfghagchiabgegahhfhdabiah":"abcdefghi",
"hbcebhhhgebbfbhgifcfaaggehbidghhefieedhiibahbceehabgficheeddeaeadbgbbcefbgbfgedccigafchaigbedacbdcbdbdcaadeiihagaabadcighiaicdhdgciiebadiedgdfibchhceh":"abcdefghi",
"hefcaibfbbifhicddiididiibbhffdiicaebhihhdbfagihhcddheihhhbacbaeabcbabffcfgiihcehhieeebbhhaabbifideibafdggdbgabdbbegdcfaeiaehcacibidhiiaaggfegdgibbcfddgfhibfdfadaiffcgfhehghbhicgfhcibbeaibhabgiddhfbbch":"abcdefghi",
"baahefgfhgdaddbffhdegdgifeeebifgccegbeiaciafdchgehbicffigddbeeagccedibcdgfghgiiaegefaefdagfhiieagicifeigbghicghdgfgfcbgbdfaddifbgigehhahhiiebbhfgdfbaeihfcfggieciedeidhcibdfigdddheghdfhabbdgfgaggiehcdceiidceaiffhfcbcfadhbcicibfafheacgdbhbiigcgchgfabcc":"abcdefghi",
"degbgjchgibedhgcdicccdhjjcegicgjejfbhijedbafgjigff":"bcdefhagji",
"hceggadbijcdhfgfhhfebfjdjhjddjhaadifbeehheejibggcfceacicjhjggddbagcgcadbeigeeeffhaaigbajdjhjjfgbibff":"abcdefghij",
"cfdeeacfedifdjedaajhhghbccgejchifehfagbbchdcaffajfgcgjhjfdjdghfdhhifjecbfbeggehfagjghhbbdgechbggjcifhegjddfgghafgcgcgahahhaeaegeghbhagbceceeefaafdgdea":"abcdefghij",
"bfdfbacjcfcghgijiejibdaghejedgajhjjibjidcfcdgdighgeebdecceihdgcfeadeijifadhjjddbiicheebfhcachchcjeiaeehfjbjfgecbiadcbebcjjbacbhjfehfbeechfbabahfgjafeigfeafhcfigaijegihggjabgfajigijdafbhfdcfeddbbiihjje":"abcdefghij",
"gicbjijdihjidagibifbeejgjjhfhjihcaihabhihjbiihaadijfgjdjjagcdaehcjhcfeffjhfjbghbbeageabhhjgfdihhbfjafaachibjaejegbbciejageigdeihhhbeejdahcgchjgebgcfgajeddebjfffjdgejggdjddjjihfihbcdddbjcbhdeedfhhghaddeggededfegjeffaejbfefbiighjacaecgdbhhihjbhegffhaef":"abcdefghij",
"pblspykdpqfhcfcirkrhbbfbnqagshfqrrkcjpsuaytjfwyhjpubttxkkpswuvoiicsnkxiyhsyqrqecsiabhvjfodpkdgcgdceobyfonnurqxvstxkgsagnosvfjgsnylyhbjcrkgaylgxxxmghfbpfqwpplntrrogtkapbpkkwkdxgrfmikdlcftuyywrsnfasxgiw":"abcdefgnosvhjklmpqituyrxw",
"jwiixcyvybhxynbwcucjxfhkrcqnyettfowekfyxnsqrcvgwyydqjtmnlrrlwufurnwsycvgvfjkpcxhpwnvbhuqwpalwttwxcurfwrjyieqesayasbkhcttsejdowgqoidaniuwgposkhvracjqfiircqgdwdxuebncxfirphxkgpytkctwxbmxkotimykmbfntwugtdhdwudnwfvyvqhkvgjnbkrjhqqrhwjdxrilsnrjrqgxbgmkhjfiywpchuifbwmiyvlrlkgusogboxrdvbucjoybspiyyvhebdivcpwicubxbxxximckpfiiclmvjgtlayohwtnyixfycrljgufcbsaqeikdddgmetpdsfqbewnxhkvqlvbayyayvqvgfjhoaawxytuky":"abcdefghijklmnrpsqvowxtuy",
"eviwfgonhmipvvbmpcmjtlmtwnhwfahwrllilwccckncyuljmgmjcscomsqbyvvhaxdxngiqmqudontknmbpuqgfecjnsflnrajrjxecjanrsmcegotmvfidusydrotsfhjsxhnfcwekhlsoconygodekjuphsbaoorilhbipgowbdyefyyjoxntrhvpydbhpddvwgdtvdxbtnasnxamnhgxiocwrxmrwmmyxlcphprwgehgedpetljovygucbqwxvkrjxkdupuprflfhmujhljkypyitykybgavirhumbacqpskiuixylscmxoqxlcvvjqkdtsarpkgtmwxfjddhgsvleskwbisgwikqmvkqirqtodoqmyoobnnovjlvlutfnwhnnwjnfrvbqdetnufqtqiuffrqyddswrictfbgunxhofjlpydfjqgdydnorkhivwcomjgbqkjtsplmlueiwgwgsmwdgtimletvnbhsprubtfaesmuxxawsxkwnsjjavfsxhekgvabwlojdncyttgjdkdsprphfjsqkjbxbfotpmydvjwokbvepoppuoqtyqaccjucfijrbfaygcefcbto":"abcdefghijklmnopqrstuvwxy",
"wugnnjdhsvjhsfabalvlpsqdayxdlwvbehakmoihrfnkvusyamwcurqsnurpetktgkieckvybcfxnannkbqjpaqqmotomsdekawunwruvuxsggeimjkpkhvlyhpduehssfnmhggkxetehmqideojgtwqtejdsgfdbdxpwktapefjysaqywgvctoowduajfrycdqxtscqocsgsvlqvcdfihbakstrwbpfeihswoejvywayoitsxehgkjvirepgjfnamniwilftquswgyrcrmfnirxtktixargkhcrsaimutfdphftxmtvaypwottqslureglmwvwakqkptnunloidvediccgtcybfbjmpcsdtkyiqgmfvhocytgkrkrrwpuptrhmmqqhuakjphpvibkbtyyqauxlldltgqwotienfpnafwycdwdfmmlluwgonlvqnbixlkrxqhoiiibykmpnjvtqtmqebbhfxhpqtyqknnkwrcqekfsconougekhqrhvpmqkcfgjnnxtrjqmkslgoyqoqlsbynidqlheoelomwetcgfakhbnhsmcsltywgcbchuqdrdsdlcgasbcncyexvoogxfenpxitrcygacygdhmisyxiabfceuxrvgjmngnapdkwolmdkhufleljqdyrjwvoqswnefcwkwnbjvdnygtlgnttwgijsvgmltnebqyuewcuhblxbipqeqmflmleiepsmakmitketbomhffggcxarabqgypjeathwwcolgpuhbeuqtyytynpwtpngwfsjimnwjahljtk":"abcdefghijklmnopqrstuvwxy",
"fduxqmmeghmsrohvpclyjmhwwxipnvqxhfmgtqtcutsbjhbmuollkwocxxdmoswsnksdflwbxetsvbuvlwtxonpyhyrodjmdbvoopfxinkojyugqegbprgqxjpghojhymsoqpylrmelsonpqrtjmjgbgmmpqklfiiaacgurrbqtbqyylfqiefbrfyotiptqujknegwjiyqybldgomccdbiikfsfnqwcilblilfwcxyytnvdrppmcslildixlungoetlqvpvpwgmhqvwwjmllomtipfavbhbahclcfdyvgyqhpxebmtovgxqtjwdiwkqtvnlumwjgvubghkcjsvkrydpasdknkdclutjcqbretopqobivwfdkqkvmwkkufwnrngfgixlinerxcnrmsbiybcxmmndhhdrwykwmgckxqhlhnabppswwkxbjpvpeplcyyhcvhjulxvvgabddcurghjurledjdatsytdkqlfyrpnasrqiyecvjtkoiuigawvqfemwwnpkhapxvaqrlnncxdepunrnimqwcinnbnifvsjkwhufoawtbeghauvxiggajubybemfyeropjwvuhjrtiggsoaddpbgfcftppwnnlgnhbrdbhycslqlfkwdiswxntapahkpsyufkthkgmbvtmbnutyhrpjhotpndnldiugmmgxmtsdxqjojaqbedotgxlgaqyempwjlvtgifybqmxvcfbuonwivfhpqrmxfakrhjrsxovxgfwcteuadldgyghvcrjaaomwisvouyqqdmdbsbuvepcaxtkuqtsvqjbmejvptmbmbxasbxadvauepxicyjnydhmsvlohnnqoevhewwmxuqingvgbniqouikflimmxpuygutamkthmkydlwtvigyeutikpvnoqisehcgaylunxgwdvanwhsbjkukxahuviutenigfmkblniwdtqxxnswjoxhqqooaltrubgbqvqqdmdmrixidgukqx":"abcdefghijklmnopqrstuvwxy",
"nfrgpdkaawogejjtsiilzbwduusydlijrbyfvacgeguvccpdvhfdxzygndxzpzwaffxgvijhyblrrjtlinysreitegavkrtbzeyzrokwhtwzegxsjbbwqczlfxndsnfxjnxhsezsmxtvkcxevrboxjqrthujosysfwpgrbpozbvugdjvgpeutulqusssruktnghecvwq":"abcdeifhmkoxjqrsygpzlutnvw",
"ojmgznybdllqahkblcickrmsfrppubzjkjxkcszeqprtnrmtpnqislrcxekuuuzbtsipvtujjulzkxaudxdhegzojdqzsyfuecfrpvqdhyyvxskpicqfyomeogckoagnzowhuogpqgueqgmtddtjepyhiphwkhlvjibnfpelhtffearwjusxnusrlabbgewycildblnepauwwpuhdxcdbbhhohadutuvkhoaafjohrvxeerfxknivvkavznkgvwfacojnkjcuqxzazeudtykpymeyiggujcithaczexffuzuxhkaqtjxbavxsmrgaektyfgtiaqjjkmegmkumiivlihlbhplybhrqmkoeohaflnbpsfaseuupyuumdgfckebamqxfamgaidrbkja":"abcdefghijknvwmtuzlopsyqxr",
"mlkjiylaeaibweoidxhryiahrokjmrrkcrvrjixacvqoyflihtdmnujbhguowocchhqzvggkwoifdkeaxgiwqfplpcdeadrnhblmkcxkiebqrcvkhchngzzxvptrjohbopxgwynpwmvnyibkmnkdmyjawvwigyywprmwvctgpnnqfawyoagagxaregkkwqkesknbxegvpcnhdnsarzrswfgsnwyytywfgbkadibubexxgomowllulvspbqqbdlkfroiypgpovouqfvvvrupoeaitrgxujchrllbqwgfoduixqhdpzczstkzoisviemgplotmtseimuufifskxjcufhpoynhtabljmtmdyuxvuzcioirqdxafkytrmlpmaxtogfgwlghvqknnicavfuvrdsxxmhdwewgcbyhqvevbwhlmghjunuxhtwmqkzvrqfzwgiliptvrcbgpbvdxsuoiajhibrzuwixtreoehjymulssobcotfffrbfobdvqirtdpqmpkcslekbhbphnglibcbhmfflyuvwoifvqdxmyvgzrhvuqlicmfooynwptfnfjuzcyqlijqfamecizktfxpcbt":"abcdefghijklmnopqrstuvwxyz",
"kpgjqizaeogmqcppxrhikwqwcjhbdghkuarxsauvleomjtkazzopgebzsjehzkdbwvbiwqsmhhimvxlhsqpmffghtbtikkdglathgierijdmlmfggdwuolmoeyiwfdisdowfxiwmatvuhmoawzzysersndkvcnkzvdyeloiexgxcexcztesfayhuvotumaxljmravuxjrfgsilrtfbhjrjfcmmxtqeamdwedgkszytcwkwgutkgfbwaggeqqzbyghbamrbtdwjohjskxevfstdcjmfohyujcdmcftjovbvozigtcgjoolufhaybjktbnvxgefivjngfgjwybjlxuyhysvsxbaaqbjyqqqanpgnunlydfrthqiyqrluyszljenavwrjbkfjvlpuoswcijgabwgiiauulqfeudfwvsmxkpewalmnpwfbtbepqyuamvfiikvnlbogwxkjvydppemrvmsaebajnmtrpdmsiuziejvpufkhmylitwenfnuxkhrclqgjnxwsgdestkimuwkypcfjabpidequwcqqeaxffapymzxuetomwtsyvudspykehiumzsjpfiilglganfeycrlvgqfjybebkttnmdjoqabyozttzvimdhzwemvwremnvallszjxyiybgzwutosidszdmlqjefjjsvpmcrveenkcceqgcutgwuxfottozwfuwhokmdrmtsjbjnrfqqwkytlkbbnxrrnbpnxgkjzawpjsnzqmtpyiyjtkecoomoobsdtayvlyanfuhahaiqfdocfmrcuoxe":"abcdefghijklmnopqrstuwxyzv",
"abaaa":"ab",
"plshnccoajplubkvdlevihwvuiohdeelzxvdovezuokpsxngzwukiaylrbercnghibultwxizpjqwjoslvuwjizkwqbyusirabwicedidzpnppxxnzbuxhlkuqqeiznpfirwkleeuweicwtxbdsregjjxugpdxnfvdsmxqynranreemwzjgqldkyrozevemiqfsxqaucojbakewpvnzteewzxptupcyzxtrforkaejdtyysvthzevtfazewirzkjvgldclmrtvycpurnjdputasvycqqizblgehghrtpansjhoxvuprhccnotmvflwbhhsspwrsxtyvedncckykbbrikosikqkuzjhgouzrlabdrrripmeliihexerxjncvjscabqlaphlbcmfgauqibxgydyvrpdknzzkllpztgohbrvdhbhfkrpsgdmwfxgwgdcdhytxjsnpuptjjvvylxogggusdmififrwugnqrfiyxskyspgakhgsjcrxcacgtemafffwpkpdscgqxggihwwqrcwolzyhkwvkbgidnxojzuenqvtynnnaorbtwmxpqwwpawehuslxbnltdjzjbkiizcollxvuhqfenesyncidxbpyijsyfciirvfptyhwpaavhailafcozzouzfqhiajnswpjdbdglmjvwlrcfnrfmwxhqlrmwejbajuulocyxouluedlkbmhwxxgzomuxnzesalwxhfttpdnmrromfrjmfbtdmyrwqhigcurusxchajdjtkpqhtzhcnahwtsgtzrpeoyfnzulngetzzyurwsbkibcwskqfcikkfyekowdsvexofkiiacvsgerqabojwlnkxnkxvuhbwmditrrujptnmsfttwwzkwmaorgmjzrgovqlcnznrnjgetwdcqqulrtiaasbnfvuvpvdiwukosgulzzgjykvaenrbiwiwebrozcremhvozrrasiuwpurghqbxdppvuhswhzdoinq":"abcdefghijklmnopqrstuvwxyz"}
return ans[s]
``` | 10 | 0 | ['Python3'] | 5 |
smallest-subsequence-of-distinct-characters | [java] [stack] [map] [4ms] | java-stack-map-4ms-by-trevor-akshay-s3zc | ```\nclass Solution {\n public String smallestSubsequence(String s) {\n \n Deque stack = new LinkedList<>();\n Map freq = new HashMap<>();\n | trevor-akshay | NORMAL | 2021-02-13T05:23:10.898284+00:00 | 2021-02-13T05:23:10.898330+00:00 | 735 | false | ```\nclass Solution {\n public String smallestSubsequence(String s) {\n \n Deque<Character> stack = new LinkedList<>();\n Map<Character,Integer> freq = new HashMap<>();\n for(char c : s.toCharArray())\n freq.put(c,freq.getOrDefault(c,0)+1);\n\n for(char c : s.toCharArray()){//abacb"\n if(!stack.isEmpty() && stack.contains(c)) {\n freq.put(c,freq.get(c)-1);\n continue;\n }\n while (!stack.isEmpty() && c <= stack.peek()\n && freq.get(stack.peek()) > 1){\n freq.put(stack.peek(),freq.get(stack.pop())-1);\n }\n stack.push(c);\n }\n StringBuilder stringBuilder = new StringBuilder();\n while (!stack.isEmpty()){\n stringBuilder.append(stack.pop());\n }\n return stringBuilder.reverse().toString();\n }\n}\n \n | 7 | 0 | ['Stack', 'Java'] | 0 |
smallest-subsequence-of-distinct-characters | Python Stack Solution Time: O(N) Space: O(1) | python-stack-solution-time-on-space-o1-b-1bgx | Thoughts on the problem: \n1). I feel like I\'ve seen this problem before. It\'s literally the same problem as 316. https://leetcode.com/problems/remove-duplica | rosemelon | NORMAL | 2019-06-09T08:00:06.732700+00:00 | 2019-06-09T08:00:17.839741+00:00 | 766 | false | Thoughts on the problem: \n1). I feel like I\'ve seen this problem before. It\'s literally the same problem as 316. https://leetcode.com/problems/remove-duplicate-letters/ Funny enough, that problem is labeled hard while this is labeled medium. Maybe there is difficulty deflation as more problems come out? You can literally paste the same exact code in both problems. \n2). The question is about parsing a string and removing letters. Usually a good idea for parsing letters (or parenthesis!) is a stack so we can have O(1) to remove a letter instead of O(N) each time. \n3). It\'s a string problem with only 26 letters of the alphabet. Great! This means we can probably do O(N) space because O(26N) is O(N). \n\nIntuition to algorithm: We count up the numbers of times each letter appears. We also keep another dictionary that remembers if a character is in our stack or not. At the beginning of each iteration, we decrement the number of times the character can still be encountered in the string in `letterDict`. \nFor each character in our string:\n1). If we have already have the letter in our stack, we skip to the next letter. \n2). If we do not have the letter in our stack and our stack is not empty, we check to see if \n\t\ta. Our current character is smaller than the last character on the stack and \n\t\tb. If the last letter in the stack still exists later on in the string \n\t\tIf a + b is true, we can pop off that last character on the stack. We keep doing a + b until it isn\'t true, then we append our current character \n3). We set that the current character is in the stack by setting it in `used`. \n\nRuntime: O(N) We need to parse the string\nSpace: O(1) We will have at most 26 letters in our stack no matter how long the string is. \n\n```\nclass Solution(object):\n def smallestSubsequence(self, s):\n """\n :type text: str\n :rtype: str\n """\n letterDict = collections.Counter(s)\n used = {letter: False for letter in "abcdefghijklmnopqrstuvwxyz"}\n stack = []\n for char in s:\n letterDict[char] -= 1\n if used[char]: continue\n while stack and ord(char) < ord(stack[-1]) and letterDict[stack[-1]] > 0:\n used[stack[-1]] = False\n stack.pop()\n stack.append(char)\n used[char] = True\n return "".join(stack)\n``` | 7 | 0 | [] | 2 |
smallest-subsequence-of-distinct-characters | C++ faster than 100%, Map based | c-faster-than-100-map-based-by-welivefre-lcc8 | Map based approach:\nThings to remember while adding or removing a character in the final string (fi)\nAdd the character if it is not present in the string till | welivefree | NORMAL | 2020-10-11T08:15:59.393588+00:00 | 2020-10-11T08:15:59.393627+00:00 | 931 | false | Map based approach:\nThings to remember while adding or removing a character in the final string (fi)\nAdd the character if it is not present in the string till now.\nRemove if:\n1. Their are more occurances of the same character ahead (Check using map)\n2. Next character in string s (s[i]) is greater than the last character in final string.\n3. s[i] is not present in the final string already.\n\n\n string removeDuplicateLetters(string s) {\n string fi;\n unordered_map<char, int> m;\n \n for(int i=0;i<s.length();i++)\n m[s[i]]++;\n \n if(fi.length()==m.size())\n return fi;\n \n for(int i=0;i<s.length();i++){\n \n while(fi.length()>0 && fi.back()>s[i] && m[fi.back()]>0 && fi.find(s[i])==-1)\n fi.pop_back();\n \n \n if(fi.find(s[i])==-1)\n fi.push_back(s[i]);\n \n m[s[i]]--;\n } \n return fi;\n }\n | 6 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | Python: Easy! Simple Solution using Stack || Time O(n) | python-easy-simple-solution-using-stack-huvdn | \nclass Solution:\n def smallestSubsequence(self, text: str) -> str:\n countMap = collections.defaultdict(int)\n stack = []\n selected = | sameerkhurd | NORMAL | 2020-09-01T07:17:09.843721+00:00 | 2020-09-01T07:17:09.843751+00:00 | 1,561 | false | ```\nclass Solution:\n def smallestSubsequence(self, text: str) -> str:\n countMap = collections.defaultdict(int)\n stack = []\n selected = set()\n\n for c in text:\n countMap[c] += 1\n\n for c in text:\n countMap[c] -= 1\n if c not in selected:\n while stack and countMap[stack[-1]] > 0 and stack[-1] > c:\n selected.remove(stack.pop())\n \n stack.append(c)\n selected.add(c)\n \n return "".join(stack)\n``` | 6 | 0 | ['Python', 'Python3'] | 1 |
smallest-subsequence-of-distinct-characters | [C++] Stack-based Solution Explained, 100% Time, ~50% Space | c-stack-based-solution-explained-100-tim-2oei | Now we have a tricky one to rein in, since we might be tempted to go for some approaches that would collapse once you factor in some specific scenarios.\n\nMy s | ajna | NORMAL | 2020-10-12T22:55:07.038980+00:00 | 2020-10-12T22:55:07.039027+00:00 | 818 | false | Now we have a tricky one to rein in, since we might be tempted to go for some approaches that would collapse once you factor in some specific scenarios.\n\nMy solution might not be the perfect one, but I found it to be rather understandable and, not secondarily, performing enough, so allow me to go into more detail about it.\n\nWe start with our usual support variables:\n* `res` will store our result, as usual;\n* `st` (I know, again: I really suck at naming) is a stack of character we will use to figure out what to keep and what to discard (more about it later);\n* `seen` is an array of `26` booleans, we will initialise to `false`;\n* `last`, similarly to the previous, is an array of `26` integers that will store the value of the last indexes of each character in the input - you don\'t really need initialising it if you use more complex logic, but setting all its values to `0` was easier and cheaper to manage;\n* `len` will store the input string size;\n\nFirst of all we are going to start populating `last` with proper values, starting from the end of the string and moving on either up to the first character or until we have met all possible `26` different ones - which probably is going to be a massive computational save on massive random strings.\n\nNote that here as when using `seen`, we will normalise all characterss to be in the `0 - 25` range subtracting `\'a\'` from their actual value.\n\nNow comes the core of our function: building and updating a stack with all the encountered characters in order; to do so, we will run through the whole string (this time from the beginning) and:\n* normalising each character `c`, as explained right above;\n* checking if `seen[c]`, in which case we just placidly `continue`;\n* otherwise, while we have something in the stack, we pop as long as `c` is lexicographically less than the current `st.top()` and if `i` is before the previously computed last index of the top of the stack (`last[st.top()]`);\n* each pop will also make so that we turn the matching cell in `seen` back to `false` (since we need to keep track about how we removed that character from our stack);\n* in any case, we add `c` on top of the stack `st`;\n* finally, we set `seen[c] = true`.\n\nOnce we are done looping through the would string, we can just pop all the content of the stack into our accumulator `res`, just remembering that this process will give us our result string in reverse, so we just have to `reverse` it again and finally can return it :)\n\nThe code:\n\n```cpp\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n // support variables\n string res = "";\n stack<char> st;\n bool seen[26];\n for (bool &s: seen) s = false;\n int last[26], len = s.size();\n for (int &l: last) l = 0;\n for (int i = len - 1, charCount = 0; charCount < 26 && i >= 0; i--) {\n // adding the last index when not yet found\n if (!last[s[i] - \'a\']) {\n charCount++;\n last[s[i] - \'a\'] = i; }\n }\n // building a stack with all the characters in a valid sequence\n for (int i = 0, c; i < len; i++) {\n c = s[i] - \'a\';\n if (seen[c]) continue;\n while (!st.empty() && c < st.top() && i < last[st.top()]) {\n seen[st.top()] = false;\n st.pop();\n }\n st.push(c);\n seen[c] = true;\n }\n // recomposing the string from the stack\n while (!st.empty()) {\n res.push_back(st.top() + \'a\');\n st.pop();\n }\n reverse(begin(res), end(res));\n return res;\n }\n};\n``` | 5 | 0 | ['String', 'Stack', 'C', 'C++'] | 2 |
smallest-subsequence-of-distinct-characters | CPP | EASY | 100% BEATS TIME AND MEM | SMALL | cpp-easy-100-beats-time-and-mem-small-by-pgon | \nstring smallestSubsequence(string text) {\n\tstack<char> st;\n\tvector<int> last(256, 0), seen(256, 0);\n\tfor(int i = 0; i < text.size(); i++)\n\t\tlast[text | hidden13 | NORMAL | 2019-07-27T12:34:27.725538+00:00 | 2019-07-27T12:34:27.725576+00:00 | 1,525 | false | ```\nstring smallestSubsequence(string text) {\n\tstack<char> st;\n\tvector<int> last(256, 0), seen(256, 0);\n\tfor(int i = 0; i < text.size(); i++)\n\t\tlast[text[i]] = i;\n\tfor(int i = 0; i < text.size(); i++){\n\t\tif(seen[text[i]])\n\t\t\tcontinue;\n\n\t\twhile(st.size() and st.top() > text[i] and last[st.top()] > i)\n\t\t\tseen[st.top()] = 0, st.pop(); \n\n\t\tst.push(text[i]), seen[text[i]] = 1;\n\t}\n\tstring res = "";\n\twhile(st.size())\n\t\tres += st.top(), st.pop();\n\treverse(res.begin(), res.end());\n\treturn res;\n}\n``` | 5 | 0 | ['Array', 'Stack', 'Greedy', 'C', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | Python stack solution with explanation | python-stack-solution-with-explanation-b-gqvz | The solution is exactly the same as for 316. Remove Duplicate Letters.\n\nSave the temporary result into a stack.\nThe stack properties:\n(1) stack can be split | otoc | NORMAL | 2019-06-10T01:07:36.782966+00:00 | 2019-06-10T03:00:13.259116+00:00 | 591 | false | The solution is exactly the same as for [316. Remove Duplicate Letters.](https://leetcode.com/problems/remove-duplicate-letters/discuss/308977/Python-stack-solution-with-explanation)\n\nSave the temporary result into a stack.\nThe stack properties:\n(1) stack can be splitted to several segments\n(2) for each segment, the characters are lexicographically increasing\n(3) except the last segment, the last character doesn\'t appear in the future\n\n```\n def smallestSubsequence(self, text: str) -> str:\n rindex = {c: i for i, c in enumerate(text)}\n stack = []\n for i, c in enumerate(text):\n if c not in stack:\n while stack and c < stack[-1] and i < rindex[stack[-1]]:\n stack.pop()\n stack.append(c)\n\t\t\t# else: c exists in stack\n\t\t\t# if stack[-1] == c: don\'t need to need to delete stack[-1] and append c\n\t\t\t# if stack[j] == c and j < len(stack) - 1: because of the stack properties, \n\t\t\t# the stack is lexicographically smaller than the new one after deleting stack[j] and appending c\n return \'\'.join(stack)\n```\n\n```\n def smallestSubsequence(self, text: str) -> str:\n count, used = 26 * [0], 26 * [0]\n for c in text:\n count[ord(c) - ord(\'a\')] += 1\n stack = []\n for c in text:\n count[ord(c) - ord(\'a\')] -= 1\n if used[ord(c) - ord(\'a\')] == 0:\n while stack and c < stack[-1] and count[ord(stack[-1]) - ord(\'a\')]:\n used[ord(stack[-1]) - ord(\'a\')] = 0\n stack.pop()\n stack.append(c)\n used[ord(c) - ord(\'a\')] = 1\n return \'\'.join(stack)\n``` | 5 | 0 | [] | 1 |
smallest-subsequence-of-distinct-characters | ✅☑[C++] || Without Stack || EXPLAINED🔥 | c-without-stack-explained-by-marksphilip-9gvj | PLEASE UPVOTE IF IT HELPED\n\n#### Same Approach in this question too: https://leetcode.com/problems/remove-duplicate-letters/solutions/4093499/c-without-stack- | MarkSPhilip31 | NORMAL | 2023-09-26T18:43:15.639244+00:00 | 2023-09-27T07:20:05.934946+00:00 | 516 | false | # *PLEASE UPVOTE IF IT HELPED*\n\n#### **Same Approach in this question too:** https://leetcode.com/problems/remove-duplicate-letters/solutions/4093499/c-without-stack-explained/\n\n---\n\n# Approach\n\n***(Also explained in the code)***\n\n#### **Step-by-Step Explanation:**\n\n1. Initialize two vectors, `count` and `used`, and an empty string `result`.\n\n - `count`: Stores the frequency of each character in the input string.\n - `used`: Keeps track of whether a character has been used in the result.\n - `result`: Will store the final lexicographically smallest string without duplicate letters.\n\n2. Iterate through the characters of the input string `s`.\n\n - For each character ch:\n - Decrement its frequency in the count vector.\n\n3. Check if the character `ch` is already used in the result.\n\n - If it\'s used, skip processing it.\n\n4. Enter a loop to remove characters from the result string if they are greater than the current character ch in lexicographical order.\n\n - This loop continues until one of the following conditions is met:\n - The `result` string is empty.\n - The last character in the `result` string is smaller than `ch`.\n - The count of the last character in the `count` vector is greater than zero.\n1. Inside the loop, mark the removed character as unused in the `used` vector and remove it from the `result` string.\n\n1. Add the current character `ch` to the `result` string and mark it as `used` in the used vector.\n\n1. After processing all characters, return the `result` string, which contains the lexicographically smallest string without duplicate letters.\n\n---\n\n\n\n# Complexity\n- **Time complexity:**\n$$O(n)$$\n\n- **Space complexity:**\n$$O(1)$$\n\n---\n\n\n\n# Code\n```\nclass Solution {\npublic:\n string removeDuplicateLetters(string s) {\n vector<int> count(26, 0); // Count the frequency of each character\n vector<bool> used(26, false); // Track if a character is already used\n string result = ""; // To store the final result\n\n for (char ch : s) {\n count[ch - \'a\']++; // Increment the frequency of the current character\n }\n\n for (char ch : s) {\n count[ch - \'a\']--; // Decrement the frequency of the current character\n\n // Check if the character is already in the result or not\n if (used[ch - \'a\']) {\n continue; // Skip if it\'s already used\n }\n\n // Remove characters from the result string if they are greater than the current character\n while (!result.empty() && ch < result.back() && count[result.back() - \'a\'] > 0) {\n used[result.back() - \'a\'] = false;\n result.pop_back();\n }\n\n result.push_back(ch); // Add the current character to the result\n used[ch - \'a\'] = true; // Mark it as used\n }\n\n return result;\n }\n};\n\n```\n# *PLEASE UPVOTE IF IT HELPED*\n\n\n---\n---\n\n | 4 | 0 | ['String', 'Stack', 'Greedy', 'Monotonic Stack', 'C++'] | 1 |
smallest-subsequence-of-distinct-characters | C++ using bitmasking and stack with detailed explainatio | c-using-bitmasking-and-stack-with-detail-kuzk | \nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n // to keep count of number of each characters in string\n vector<int> co | ishanrai05 | NORMAL | 2020-10-11T21:14:17.768380+00:00 | 2020-10-11T21:14:56.608843+00:00 | 335 | false | ```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n // to keep count of number of each characters in string\n vector<int> count(26);\n \n // bit mask to mark the characters that are already present in the stack\n int visited=0;\n \n // we will use stack to keep track of characters that are less than current \n // characters and appear in later part of the string\n stack<int> st;\n \n \n int n=s.size();\n for (char ch:s){\n count[ch-\'a\']++;\n }\n \n \n for (int i=0;i<n;i++){\n // bring characters into the range 0-25\n int ch = s[i]-\'a\';\n \n // decrease the count of characters\n count[ch]--;\n \n // if the character is already present in the stack then we don\'t need to do anythinh\n if (((1<<ch)&visited)>0) continue;\n\n // if the character at the top of the stack is less than the current character and there are\n // more of it left, i.e. it occurs later in the string then remove it\n while (!st.empty() and st.top()>ch and count[st.top()]>0){\n \n // mark it univisited since no longer present in the stack\n visited = visited & ~(1<<st.top());\n st.pop();\n }\n \n // push the characters in the stack and mark it visited\n st.push(ch);\n visited = visited|(1<<ch);\n }\n string ans="";\n while (!st.empty()){\n char ch = \'a\'+st.top();\n st.pop();\n \n // the characters in the stack will be in reverse order of their appearance in the string\n ans.insert(ans.begin(),ch);\n }\n return ans;\n }\n};\n``` | 4 | 0 | [] | 1 |
smallest-subsequence-of-distinct-characters | Python and Java solution. | python-and-java-solution-by-aadesh_hemwa-an7s | Steps:\n1. a dictionary/map with Last occurance of each character in the String.\n2. a stack that will help us keep track of the last inserted Character.\n3. fo | aadesh_hemwani | NORMAL | 2020-10-11T11:07:18.444090+00:00 | 2020-10-12T14:59:41.640698+00:00 | 477 | false | **Steps:**\n1. a dictionary/map with Last occurance of each character in the String.\n2. a stack that will help us keep track of the last inserted Character.\n3. for each character, we check if we have pushed it into the stack earlier, we use a set for Fast Lookups.\n4. if the character is present in SET do nothing with that character.\n5. otherwise, check if the character at the top of the stack is greater than the current Character (to maintain lexicographical order, Eg: b is greater than a).\n6. if so, we pop the Greater character and we push the current smaller character.\n8. one think to worry about before we pop the top character is to check if we will see the top character again later in the string, we do this by checking the last Occurance Dict/Map.\n7. finally we convert the stack/list into a string.\n\n**Python:**\n```\nclass Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n lastPos = {}\n for i in range(len(s)): lastPos[s[i]] = i\n stack = []\n seen= set()\n for i in range(len(s)):\n if s[i] in seen: continue\n while stack and stack[-1] > s[i] and lastPos[stack[-1]] > i:\n p = stack.pop()\n seen.remove(p)\n stack.append(s[i])\n seen.add(s[i])\n return "".join(stack)\n```\n\n**Java:**\n```\nclass Solution {\n public String smallestSubsequence(String s) {\n Map<Character, Integer> lastPos = new HashMap<>();\n for(int i=0; i<s.length(); ++i) lastPos.put(s.charAt(i), i);\n Stack<Character> stack = new Stack<>();\n Set<Character> seen = new HashSet<>();\n for(int i=0; i<s.length(); ++i){\n char curr = s.charAt(i);\n if(seen.contains(curr)) continue;\n while(!stack.isEmpty() && stack.peek() > curr && lastPos.get(stack.peek()) > i){\n char p = stack.pop();\n seen.remove(p);\n }\n stack.add(curr);\n seen.add(curr);\n }\n String ans = "";\n for(char c: stack) ans+=c;\n return ans;\n }\n}\n``` | 4 | 1 | [] | 1 |
smallest-subsequence-of-distinct-characters | 1ms, beats 100% JAVA solution with explanation | 1ms-beats-100-java-solution-with-explana-a4ru | \n// solution is pretty simple and straight forward\n// first we count the frequency of each char in the string\n// then we put each char of the string in the s | anishrajan25 | NORMAL | 2020-09-23T13:24:20.039530+00:00 | 2020-09-23T13:32:27.769168+00:00 | 639 | false | ```\n// solution is pretty simple and straight forward\n// first we count the frequency of each char in the string\n// then we put each char of the string in the string res(the string that we\'ll be returning)\n// if we find a char x (in text) that is smaller than the last char in our res string\n// then we remove the char from the end of the res string\n// then we will add the char x at the end of our res string\n// this will ensure that the res will be lexicographically smallest subsequence of text\n\nclass Solution {\n public String smallestSubsequence(String text) {\n int[] freq = new int[26];\n boolean[] taken = new boolean[26];\n \n for(char c: text.toCharArray()) freq[c - \'a\']++;\n \n StringBuilder res = new StringBuilder();\n res.append(\'0\');\n \n for(char c: text.toCharArray()) {\n freq[c-\'a\']--;\n if(!taken[c - \'a\']) {\n while(res.charAt(res.length() - 1) > c && freq[res.charAt(res.length() - 1) - \'a\'] > 0) {\n taken[res.charAt(res.length() - 1) - \'a\'] = false;\n res.deleteCharAt(res.length() - 1);\n }\n res.append(c);\n taken[c-\'a\'] = true;\n }\n }\n \n return res.substring(1).toString();\n }\n}\n``` | 4 | 2 | ['Java'] | 0 |
smallest-subsequence-of-distinct-characters | C++ Solution with Detailed Explanation | c-solution-with-detailed-explanation-by-etf6n | Problem is to remove duplicates and output a string with unique characters while maintaing the smallest(lexicographically) permutation of all possible subsequen | rootkonda | NORMAL | 2020-05-21T14:25:34.192424+00:00 | 2020-05-21T14:25:34.192472+00:00 | 364 | false | Problem is to remove duplicates and output a string with unique characters while maintaing the smallest(lexicographically) permutation of all possible subsequences of distinct characters.\n\n1. We have to just keep adding the unique characters to the answer and while adding them we have to check if the character to be added is smaller than the character which we have added previuosly to the answer. \n2. If it is smaller, then we can check whether the previous character is available for use in future iterations ? If yes, then we can just remove the character we added previously. Repeat this step, until we find a previous character smaller than current character.\n3. We can now add the current character to the answer.\n\n```\n class Solution {\n public:\n string smallestSubsequence(string text)\n {\n int last[26] = {};\n int seen[26] = {};\n int n = (int)text.size();\n string ans="";\n for(int i=0;i<n;i++)\n last[text[i]-\'a\'] = i; // In order to know the last occurence of a character(step 2 above).At any point if we want to know that a given character is available in the future iterations.\n \n for(int i=0;i<n;i++)\n {\n if(seen[text[i]-\'a\'])\n continue;\n seen[text[i]-\'a\']++; // To avoid adding duplicates\n while(!ans.empty() and ans.back()>text[i] and i<last[ans.back()-\'a\']) // As explained in step 2 above.\n {\n seen[ans.back()-\'a\'] = 0; // We have to reset this character in seen to 0 because when it comes again in future, it has to be added to the answer again.\n ans.pop_back();\n }\n \n ans.push_back(text[i]);\n }\n return ans;\n }\n};\n\n\n``` | 4 | 0 | [] | 1 |
smallest-subsequence-of-distinct-characters | python stack | python-stack-by-nightybear-qywg | python\nclass Solution:\n \'\'\'\n Time complexity : O(n)\n Space complexity : O(n)\n \'\'\'\n def smallestSubsequence(self, text: str) -> str:\n | nightybear | NORMAL | 2020-05-17T08:14:00.518030+00:00 | 2020-05-17T08:14:00.518065+00:00 | 386 | false | ```python\nclass Solution:\n \'\'\'\n Time complexity : O(n)\n Space complexity : O(n)\n \'\'\'\n def smallestSubsequence(self, text: str) -> str:\n count = collections.Counter(text)\n visited, stack = set(), []\n \n for ch in text:\n count[ch] -= 1\n if ch not in visited:\n # if stack[-1] > ch and stack[-1] will comes in later, we can remove it\n while stack and stack[-1] > ch and count[stack[-1]] > 0:\n visited.remove(stack.pop())\n stack.append(ch)\n visited.add(ch)\n \n return \'\'.join(stack)\n\n``` | 4 | 0 | ['Stack', 'Python3'] | 1 |
smallest-subsequence-of-distinct-characters | Basic Explanation | basic-explanation-by-be-humble-extn | \n/*\n Using Monotonic Increasing Stack\n \n Example : cdadabcc\n\t\n Character Count : \n c->3\n d->2\n a->2\n b->1\n \n\tIterating | be-humble | NORMAL | 2020-03-16T17:34:34.522668+00:00 | 2020-03-16T17:36:40.180083+00:00 | 391 | false | ```\n/*\n Using Monotonic Increasing Stack\n \n Example : cdadabcc\n\t\n Character Count : \n c->3\n d->2\n a->2\n b->1\n \n\tIterating to the given input string one by one : \n\t(Popping element from the stack only when element freq. is greater than one)\n\t\n "c" : c \n "d" : c d\n "a" : a\n \n c->2\n d->1\n a->2\n b->1\n \n "d" : a d\n "a" : this is already present in current stack\n \n c->2\n d->1\n a->1\n b->1\n \n "b" : a d b\n "c" : a d b c\n "c" this already present in current stack\n \n c->1\n d->1\n a->1\n b->1\n \n final stack -> a d b c\n \n*/\n``` | 4 | 0 | [] | 1 |
smallest-subsequence-of-distinct-characters | Java | Stack | Greedy | O(n) Time and Memory | java-stack-greedy-on-time-and-memory-by-cvzzs | \nclass Solution {\n public String smallestSubsequence(String text) {\n StringBuilder sb = new StringBuilder(); \n Stack<Character> st = new St | tacoman | NORMAL | 2019-09-29T06:52:19.441686+00:00 | 2019-09-29T06:52:19.441735+00:00 | 890 | false | ```\nclass Solution {\n public String smallestSubsequence(String text) {\n StringBuilder sb = new StringBuilder(); \n Stack<Character> st = new Stack<>();\n boolean[] visited = new boolean[26]; \n int[] counts = new int[26];\n for(char ch : text.toCharArray()) counts[ch-\'a\']++; \n for(char ch : text.toCharArray()) {\n counts[ch-\'a\']--; \n if(visited[ch-\'a\']) continue; \n while(!st.isEmpty() && st.peek() > ch && counts[st.peek()-\'a\'] > 0) { \n visited[st.pop()-\'a\'] = false;\n }\n st.push(ch); \n visited[ch-\'a\'] = true;\n }\n while(!st.isEmpty()) sb.append(st.pop()); \n sb.reverse(); \n return new String(sb); \n }\n}\n``` | 4 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | Runtime Beats 3ms🔥 | 2 Solutions : Monotonic Stack | O(1) Space | 🔥Self Explanatory Comments🔥 | runtime-beats-3ms-2-solutions-monotonic-f8666 | \uD83D\uDE0A ~ \uD835\uDE52\uD835\uDE5E\uD835\uDE69\uD835\uDE5D \u2764\uFE0F \uD835\uDE57\uD835\uDE6E \uD835\uDE43\uD835\uDE5E\uD835\uDE67\uD835\uDE5A\uD835\uDE | hirenjoshi | NORMAL | 2023-10-10T08:39:46.985854+00:00 | 2023-12-26T04:44:42.656051+00:00 | 368 | false | \uD83D\uDE0A ~ \uD835\uDE52\uD835\uDE5E\uD835\uDE69\uD835\uDE5D \u2764\uFE0F \uD835\uDE57\uD835\uDE6E \uD835\uDE43\uD835\uDE5E\uD835\uDE67\uD835\uDE5A\uD835\uDE63\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n***Hey There It\'s Easy! Just Take A Look At The Code And Comments Within It. You\'ll Get It.\nStill Have Doubts! Feel Free To Comment, I\'ll Definitely Reply.***\n\n***Hey Everyone! If You Loved This Problem Than I Wanna Prefer An Another One Too Its Because It\'s The Exact Copy Of This Problem And It is :-\n"316 - Remove Duplicate Letters"\nThe Intuition & The Code Of "Leetcode 316" Is The Exact Same As This One, Hence I Want You To Try This "Leetcode 316" Yourself, First!***\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n***Both Accepted :\n-> Using 1 Stack\n-> Using Constant Auxiliary Space***\n\n# Complexity\n- *Time complexity: Mentioned in the code*\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- *Space complexity: Mentioned in the code*\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n**Approach 1 : Using 1 Stack**\n```\n// #1 Method to find the lexicographically smallest subsequence, using 1 stack - O(N) & O(N)\nstd::string smallestSubsequence(std::string s) {\n int n = s.size();\n\n std::string output = ""; // Stores the result string (output).\n std::vector<bool> isTaken(26); // Avoids the letter duplications.\n std::vector<int> lastSeenIdx(26); // Maps the letters with their index at which they\'re seen at last.\n std::stack<char> st; // Maintains letters for building the smallest lexicographic subsequence.\n\n // Map the letters with their index at which they\'re seen at last.\n for(int i=0; i<n; i++) {\n lastSeenIdx[s[i]-\'a\'] = i;\n }\n\n for(int i=0; i<n; i++) {\n char currLetter = s[i];\n // If its possible to take the current-letter (ith letter).\n if(!isTaken[currLetter-\'a\']) {\n // Pop all the letters smaller than the ith letter.\n while(!st.empty() && lastSeenIdx[st.top()-\'a\'] > i && st.top() > currLetter) {\n isTaken[st.top()-\'a\'] = false;\n st.pop();\n }\n // Push the ith letter to the stack.\n st.push(currLetter);\n // Mark the ith letter untakable for the next time, as we are aiming for the distinct letters.\n isTaken[currLetter-\'a\'] = true;\n } \n }\n\n // Pop and store each letter to the result string (output).\n while(!st.empty()) {\n output.push_back(st.top());\n st.pop();\n }\n\n // Reverse the result string to get the lexicographically smallest subsequence.\n std::reverse(begin(output), end(output));\n \n // Return the result string (output).\n return output;\n}\n```\n**Approach 2 : Using Constant Auxiliary Space**\n```\n// #2 Method to find the lexicographically smallest subsequence, using constant auxiliary space - O(N) & O(1)\nstd::string smallestSubsequence(std::string s) {\n int n = s.size();\n\n std::vector<bool> isTaken(26); // Avoids the letter duplications.\n std::vector<int> lastSeenIdx(26); // Maps the letters with their index at which they\'re seen at last.\n std::string output = ""; // Stores the result string (output).\n\n // Map the letters with their index at which they\'re seen at last.\n for(int i=0; i<n; i++) {\n lastSeenIdx[s[i]-\'a\'] = i;\n }\n\n for(int i=0; i<n; i++) {\n char currLetter = s[i];\n // If its possible to take the current-letter (ith letter).\n if(!isTaken[currLetter-\'a\']) {\n // Pop all the letters smaller than the ith letter.\n while(!output.empty() && lastSeenIdx[output.back()-\'a\'] > i && output.back() > currLetter) {\n isTaken[output.back()-\'a\'] = false;\n output.pop_back();\n }\n // Push the ith letter to the "output".\n output.push_back(currLetter);\n // Mark the ith letter untakable for the next time, as we are aiming for the distinct letters.\n isTaken[currLetter-\'a\'] = true;\n } \n }\n\n // Return the result string (output).\n return output;\n}\n```\n\uD835\uDDE8\uD835\uDDE3\uD835\uDDE9\uD835\uDDE2\uD835\uDDE7\uD835\uDDD8 \uD835\uDDDC\uD835\uDDD9 \uD835\uDDEC\uD835\uDDE2\uD835\uDDE8 \uD835\uDDDF\uD835\uDDDC\uD835\uDDDE\uD835\uDDD8 \uD835\uDDE7\uD835\uDDDB\uD835\uDDD8 \uD835\uDDE6\uD835\uDDE2\uD835\uDDDF\uD835\uDDE8\uD835\uDDE7\uD835\uDDDC\uD835\uDDE2\uD835\uDDE1 \uD83D\uDC4D | 3 | 0 | ['String', 'Stack', 'Greedy', 'Monotonic Stack', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | ✅EASY C++ SOLUTION using STACK✅ | easy-c-solution-using-stack-by-2005115-ebho | PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT\n# CONNECT WITH ME\n### https://www.linkedin.com/in/pratay-nandy-9ba57b229/\n#### https://www.instagram.com/pratay_nand | 2005115 | NORMAL | 2023-09-26T08:00:01.135297+00:00 | 2023-09-26T08:00:01.135321+00:00 | 741 | false | # **PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT**\n# **CONNECT WITH ME**\n### **[https://www.linkedin.com/in/pratay-nandy-9ba57b229/]()**\n#### **[https://www.instagram.com/pratay_nandy/]()**\n\n# Approach\nThe provided C++ code is an implementation of the "Smallest Subsequence" problem. The goal of this problem is to remove duplicate letters from a given string while maintaining the lexicographical order of the remaining letters.\n\nHere\'s an explanation of the approach:\n\n- Create a stack st to store characters as you iterate through the input string s.\n\n- Create two vectors:\n\n1. `lastindex`: It stores the last index where each character appears in the string s. This information helps in deciding when to remove characters from the stack.\n2. `seen`: It tracks whether a character has been added to the stack or not to avoid duplicates.\n- Iterate through the string s to populate the lastindex vector. For each character, update its corresponding index in the lastindex vector.\n\nIterate through the string s again:\n\n- For each character `s[i]`, check if it has already been seen (i.e., if `seen[curr]` is true). If it has been seen, skip it.\nIf it hasn\'t been seen:\n- While the stack is not empty, the character at the top of the stack `(st.top())` is greater than the current character `s[i]`, and there\'s still a remaining occurrence of the character after the current index (i.e., `i < lastindex[st.top()-\'a\'])`, pop characters from the stack and mark them as unseen `(seen[st.top() - \'a\'] = false)` to ensure that the smaller characters appear later.\n- Push the current character`s[i]` onto the stack and mark it as seen (`seen[curr] = true`).\n- After processing all characters in the input string, the stack `st` contains the characters to keep in the lexicographical order.\n\n- Build the result string `res` by popping characters from the stack and reversing it (since the characters were pushed onto the stack in reverse order).\n\n- Return the result string as the final answer.\n\nThis approach ensures that the characters in the result string are in lexicographical order, and duplicates are removed. The order is preserved by considering the last index of each character and removing characters from the stack when necessary.\n\n\n<!-- Describe your approach to solving the problem. -->\n\n<!-- # Complexity -->\n<!-- - Time complexity: -->\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- - Space complexity: -->\n\n# Code\n```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n stack<char>st;\n vector<int>lastindex(26,0);\n vector<bool>seen(26,false);\n for(int i = 0 ;i<s.size();i++)\n {\n lastindex[s[i] - \'a\'] = i; \n }\n for(int i = 0 ;i<s.size();i++)\n {\n int curr = s[i] - \'a\'; \n if(seen[curr])\n {\n continue;\n }\n while(st.size() > 0 && st.top() > s[i] && i < lastindex[st.top()-\'a\'])\n {\n seen[st.top() - \'a\'] = false;\n st.pop();\n }\n st.push(s[i]);\n seen[curr] = true; \n }\n string res= "";\n while(st.size() > 0)\n {\n res += st.top();\n st.pop();\n }\n reverse(res.begin(),res.end());\n return res;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
smallest-subsequence-of-distinct-characters | 🏆O(N)🏆 || ✅Explained in Video✅ || 🔥Begineer friendly🔥 | on-explained-in-video-begineer-friendly-pzzzn | Intuition\nVideo link for better understaning:\n\nhttps://youtu.be/rU5p0MRm5zU?si=Fy_mT3DgCZeT-X9i\n\n\n# Complexity\n- Time complexity:\n O(N)\n\n- Space comp | rajh_3399 | NORMAL | 2023-09-26T06:42:56.145954+00:00 | 2023-09-26T06:42:56.145973+00:00 | 198 | false | # Intuition\n**Video link for better understaning:**\n\n[https://youtu.be/rU5p0MRm5zU?si=Fy_mT3DgCZeT-X9i]()\n\n\n# Complexity\n- Time complexity:\n O(N)\n\n- Space complexity:\n O(26)\n\n# Code\n```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n int n = s.size();\n string result; // for final result store\n vector<bool>taken(26,false); \n vector<int>last_idx(26);\n\n for(int i = 0 ; i< n ; i++){\n char ch = s[i];\n last_idx[ch - \'a\'] = i;\n }\n\n for(int i = 0 ; i < n ; i++){\n char ch = s[i];\n int idx = ch - \'a\';\n if(taken[idx] == true) continue;\n while(result.size() > 0 && result.back() > ch && last_idx[result.back() -\'a\'] > i){\n taken[result.back() -\'a\'] = false;\n result.pop_back();\n }\n result.push_back(ch);\n taken[idx] = true;\n } \n return result;\n }\n};\n``` | 3 | 0 | ['Monotonic Stack', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | C++ EASY AND CLEAN SOLUTION USING STACK | c-easy-and-clean-solution-using-stack-by-vh34 | Code\n\nclass Solution {\npublic:\n string smallestSubsequence(string text) {\n vector<int> freq(26,0);\n vector<int> vis(26,0);\n stack | arpiii_7474 | NORMAL | 2023-08-02T06:13:40.297396+00:00 | 2023-08-02T06:13:40.297426+00:00 | 628 | false | # Code\n```\nclass Solution {\npublic:\n string smallestSubsequence(string text) {\n vector<int> freq(26,0);\n vector<int> vis(26,0);\n stack<char> st;\n for(auto it:text) freq[it-\'a\']++;\n for(int i=0;i<text.size();i++){\n char c=text[i];\n freq[c-\'a\']--;\n if(vis[c-\'a\']) continue;\n while(!st.empty() && st.top()>c && freq[st.top()-\'a\']>0){\n vis[st.top()-\'a\']--;\n st.pop();\n }\n vis[c-\'a\']++;\n st.push(c);\n }\n string str="";\n while(!st.empty()){\n str=str+st.top();\n st.pop();\n }\n reverse(str.begin(),str.end());\n return str;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
smallest-subsequence-of-distinct-characters | ✅✅Faster || Easy To Understand || C++ Code | faster-easy-to-understand-c-code-by-__kr-el1y | Using Monotonic Stack\n\n Time Complexity :- O(N)\n\n Space Complexity :- O(N)\n\n\nclass Solution {\npublic:\n string smallestSubsequence(string str) {\n | __KR_SHANU_IITG | NORMAL | 2022-10-05T19:10:21.763697+00:00 | 2022-10-05T19:10:21.763734+00:00 | 1,975 | false | * ***Using Monotonic Stack***\n\n* ***Time Complexity :- O(N)***\n\n* ***Space Complexity :- O(N)***\n\n```\nclass Solution {\npublic:\n string smallestSubsequence(string str) {\n \n int n = str.size();\n \n // declare a stack, this will store the character in increasing order\n \n stack<char> st;\n \n vector<int> last_index(26, -1);\n \n // store the last index of every character\n \n for(int i = 0; i < n; i++)\n {\n last_index[str[i] - \'a\'] = i;\n }\n \n // curr_set will keep track of included characters\n \n unordered_set<char> curr_set;\n \n for(int i = 0; i < n; i++)\n {\n // if the curr character is included then simply skip it\n \n if(curr_set.count(str[i]))\n {\n continue;\n }\n \n // pop the largest character from top, if the top element is present to the right of i\n \n while(!st.empty() && st.top() > str[i] && last_index[st.top() - \'a\'] > i)\n {\n curr_set.erase(st.top());\n \n st.pop();\n }\n \n // add the curr character\n \n st.push(str[i]);\n \n curr_set.insert(str[i]);\n }\n \n // make the res array\n \n string res = "";\n \n while(st.empty() == false)\n {\n res += st.top();\n \n st.pop();\n }\n \n // reverse the res\n \n reverse(res.begin(), res.end());\n \n return res;\n }\n};\n``` | 3 | 0 | ['Stack', 'C', 'C++'] | 1 |
smallest-subsequence-of-distinct-characters | C++ ||Explained || Stack || Greedy || Easy-Understanding | c-explained-stack-greedy-easy-understand-94ji | \nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n \n // in string type of subsequence problem \n \n //stack | KR_SK_01_In | NORMAL | 2022-10-05T18:40:14.880863+00:00 | 2022-10-05T18:40:14.880910+00:00 | 1,236 | false | ```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n \n // in string type of subsequence problem \n \n //stack is always going to be a option \n \n //condition of popping -> curr character(s[i]) , popping character (stk.top())\n \n // i) popping character must be present on the right side , present right side of s[i]\n \n // popping character must be greater than curr character (lexicographically)\n \n // there may be the case that curr charceter is smaller than stk.top()\n \n // popping charcter , but already present in the stack \n \n // take care of these conditions\n \n vector<int> index(26 , -1);\n \n for(int i=0;i<s.size();i++)\n {\n index[s[i]-\'a\']=i;\n }\n \n stack< char > stk;\n \n unordered_set< char > st;\n \n for(int i=0;i<s.size();i++)\n {\n while(!stk.empty() && index[stk.top()-\'a\']>i && s[i]<stk.top() && st.find(s[i])==st.end())\n {\n st.erase(stk.top());\n stk.pop();\n }\n \n if(st.find(s[i])==st.end())\n {\n stk.push(s[i]);\n st.insert(s[i]);\n }\n }\n \n string res="";\n \n while(!stk.empty())\n {\n res.push_back(stk.top());\n stk.pop();\n }\n \n reverse(res.begin() , res.end());\n \n return res;\n \n }\n};\n``` | 3 | 0 | ['Stack', 'Greedy', 'C', 'C++'] | 1 |
smallest-subsequence-of-distinct-characters | ✅[C++] Using Stack | Monotonic for characters | c-using-stack-monotonic-for-characters-b-m4di | Concept Used : Monotonic Stack\nSince, we are asked to find a subsequence having all the characters and that too in lexicographical order, therefore stack and p | biT_Legion | NORMAL | 2022-06-30T20:44:01.082942+00:00 | 2022-06-30T20:44:01.082968+00:00 | 476 | false | #### Concept Used : Monotonic Stack\nSince, we are asked to find a subsequence having all the characters and that too in lexicographical order, therefore stack and priority queue should come to your mind. Now, we cannot maintain the relative order with priority queue since it places the smallest at top, but if we need to find an increasing or decreasing subsequence, we choose ***monotonic stack***. \nIn case, you dont know about it, please solve some questions and have a good knowledge of this concept because its widely used in many stack problems. \nHere, we find a subsequence having exactly one occurance of each character and that should be in increasing/lexicographical order. Therefore, we use monotonically increasing stack. Along with it, we maintain a visited array that keeps the check of which elements are present in stack. \nSo, we loop over the string, at each iteration, we decrease the hash of that character, and if stack is empty, we put it in the stack, else, if it is not already present in the stack, then to make it a part of our answer, we put it at its right position, by removing all the characters greater than it. Please note that, if we have an additional condition that `hash[st.top()-\'a\']!=0`, which means we will pop the character from the stack if and only if that occurance of that character is not the last character. If it is the last occurance of that character, we need to keep it in the stack. We cannot pop it. \nFinally, we just put all the characters in an answer string and return it. :) \n\n```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n stack <char> st;\n vector <int> hash(26,0);\n vector <bool> visited(26,false);\n for(auto u : s) hash[u-\'a\']++;\n \n for(int i = 0; i<s.size(); i++){\n hash[s[i]-\'a\']--;\n if(st.empty()) st.push(s[i]),visited[s[i]-\'a\']=true;\n else{\n if(!visited[s[i]-\'a\']){\n while(!st.empty() and s[i]<st.top() and hash[st.top()-\'a\']!=0){ \n visited[st.top()-\'a\']=false;\n st.pop();\n }\n st.push(s[i]), visited[s[i]-\'a\']=true;\n }\n }\n }\n string ans = "";\n while(!st.empty()) ans.push_back(st.top()), st.pop();\n reverse(ans.begin(),ans.end());\n return ans;\n }\n};\n``` | 3 | 0 | ['Stack', 'C', 'Monotonic Stack', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | [C++] | Unordered Map | Easy Understanding | c-unordered-map-easy-understanding-by-pr-jnym | ```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n unordered_mapmp;\n \n for(int i=0;ivisited(26,false);\n | pranali_lahoti | NORMAL | 2022-03-18T18:16:35.448401+00:00 | 2022-03-18T18:16:35.448451+00:00 | 569 | false | ```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n unordered_map<char,int>mp;\n \n for(int i=0;i<s.length();i++)mp[s[i]]=i; //store last index of occurance\n \n vector<bool>visited(26,false);\n \n string result = "";\n for(int i=0;i<s.length();i++){\n if(visited[s[i] - \'a\'])continue;\n \n while(!result.empty() && result.back() > s[i] && mp[result.back()] > i){\n visited[result.back()-\'a\'] = false;\n result.pop_back();\n }\n result.push_back(s[i]);\n visited[s[i] - \'a\'] = true;\n }\n return result;\n }\n}; | 3 | 0 | ['Array', 'C', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | JAVASCRIPT ||Effective Solution || Easy To Understand || With Explanation ||Beginner Friendly|| | javascript-effective-solution-easy-to-un-rwbn | \nvar removeDuplicateLetters = function(s) {\n let stk = []; // Create a stack ie, an array\n for(let i = 0; i < s.length; i++){ //loop through the string | VaishnaviRachakonda | NORMAL | 2022-03-18T12:46:07.586967+00:00 | 2022-03-18T12:46:07.587000+00:00 | 333 | false | ```\nvar removeDuplicateLetters = function(s) {\n let stk = []; // Create a stack ie, an array\n for(let i = 0; i < s.length; i++){ //loop through the string\n let letter = s[i]; \n if(stk.includes(letter)) //if the stk already contains the letter skip \n continue;\n while(stk[stk.length-1] > letter && s.substring(i).includes(stk[stk.length-1])) \n\t\t{\n\t\t/*peek stack and check if the top letter has higher order than incoming letter and\n\t\tthe top letter must be present in the remaining sub-sting. */\n stk.pop(); //pop all such elements\n\t\t}\n stk.push(letter); //push the letter\n }\n return stk.join(\'\'); //convert the stk into a string and return it.\n};\n```\n\nIts okay if you did not get the solution in the first try, don\'t give up!\nPlease do UPVOTE if you find it helpfull.... I know this is not the best solution to this problem but this is what I came up with.\nHave fun Coding!! Cheers! | 3 | 1 | ['Monotonic Stack', 'JavaScript'] | 1 |
smallest-subsequence-of-distinct-characters | Stack Solution 0(n) | stack-solution-0n-by-itz_pankaj-qpy9 | From the input string, we are trying to greedily build a monotonically increasing result string. If the next character is smaller than the back of the result st | itz_pankaj | NORMAL | 2021-05-29T06:37:46.325311+00:00 | 2021-05-29T06:37:46.325340+00:00 | 213 | false | From the input string, we are trying to greedily build a monotonically increasing result string. If the next character is smaller than the back of the result string, we remove larger characters from the back providing there are more occurrences of that character later in the input string.\n\n**Time Complexity:**\nTime O(N)\nSpace O(26) i.e. constant space as We need the constant memory to track up to 26 unique letters.\n\n**Implementation**\n\n```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n vector<char> st;\n \n vector<int> ct(26,0);\n vector<int> visi(26,0);\n for(auto &x:s) \n ct[x-\'a\']++;\n \n for(auto&x:s)\n { \n ct[x-\'a\']--;\n \n if(visi[x-\'a\']==0)\n {\n while(st.size()!=0 && x < st.back() && ct[st.back()-\'a\']>0)\n { \n visi[st.back() - \'a\']=0;\n st.pop_back();\n }\n visi[x-\'a\']=1;\n st.push_back(x);\n }\n }\n \n string res = "" ;\n for(auto &x : st)\n res += x;\n return res;\n \n }\n};\n``` | 3 | 0 | [] | 1 |
smallest-subsequence-of-distinct-characters | [Python3] stack O(N) | python3-stack-on-by-ye15-0gt2 | Algo\nScan through s via a stack. If the current character is not in stack, we pop out characters in stack from the top that are larger than the current one and | ye15 | NORMAL | 2020-10-14T17:45:45.303188+00:00 | 2021-01-14T03:41:11.783117+00:00 | 367 | false | **Algo**\nScan through `s` via a `stack`. If the current character is not in stack, we pop out characters in stack from the top that are larger than the current one and are still available later in `s`. \n\n**Implementation**\n```\nclass Solution:\n def smallestSubsequence(self, s: str) -> str:\n loc = {x: i for i, x in enumerate(s)}\n stack = []\n for i, x in enumerate(s): \n if x not in stack: \n while stack and x < stack[-1] and i < loc[stack[-1]]: stack.pop()\n stack.append(x)\n return "".join(stack)\n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)` | 3 | 0 | ['Python3'] | 1 |
smallest-subsequence-of-distinct-characters | Tail Recursion in Java | tail-recursion-in-java-by-namandeept-a259 | Idea : Always consider the first character alphabetically which will give yes to the trailing output based on the content stored in the set, and append that cha | namandeept | NORMAL | 2020-10-11T17:52:24.983665+00:00 | 2020-10-11T17:52:24.983702+00:00 | 454 | false | **Idea** : Always consider the first character alphabetically which will give yes to the trailing output based on the content stored in the set, and append that character to the new String and remove that character from the present set. \nCode :\n```\nclass Solution {\n public boolean contains(Set<Character>set,String ch){\n Set<Character>nset = new HashSet<>();\n for(char c : ch.toCharArray()){\n if(set.contains(c)) nset.add(c);\n }\n return nset.size() == set.size();\n }\n public String solve(String ch,Set<Character>set){\n if(set.size()==0){\n return "";\n }\n for(char c= \'a\';c<=\'z\';c++){\n if(set.contains(c)){\n int index = ch.indexOf(c);\n String ch_ = ch.substring(index);\n if(contains(set,ch_)){\n set.remove(c);\n return c + solve(ch_,set);\n }\n }\n }\n return "";\n }\n public String smallestSubsequence(String s) {\n Set<Character>set = new HashSet<>();\n for(char ch : s.toCharArray()){\n set.add(ch);\n }\n return solve(s,set);\n }\n}\n``` | 3 | 0 | ['Greedy', 'Recursion', 'Java'] | 1 |
smallest-subsequence-of-distinct-characters | C++, O(n) time complexity and O(1) memory | c-on-time-complexity-and-o1-memory-by-hu-men3 | \nclass Solution {\npublic:\n string smallestSubsequence(string str) {\n string res;\n unordered_map<char, int> m;\n \n for (auto | huawenli | NORMAL | 2020-09-04T03:32:32.540836+00:00 | 2020-09-04T03:32:32.540887+00:00 | 383 | false | ```\nclass Solution {\npublic:\n string smallestSubsequence(string str) {\n string res;\n unordered_map<char, int> m;\n \n for (auto c: str) m[c]++;\n if (str.size() == m.size()) return str;\n \n for (int i = 0; i < str.size(); i++) {\n while (res.size() > 0 && res.back() > str[i] && m[res.back()] > 0 && (res.find(str[i]) == string::npos)) {\n res.pop_back();\n }\n if (res.find(str[i]) == string::npos) {\n res.push_back(str[i]);\n }\n m[str[i]]--;\n }\n return res;\n }\n};\n``` | 3 | 1 | [] | 0 |
smallest-subsequence-of-distinct-characters | Python solution | python-solution-by-hkm001-cgat | \n s = []\n for i,t in enumerate(text):\n if t not in s:\n while s and ord(t) <= ord(s[-1]) and s[-1] in text[i+1:]:\n | hkm001 | NORMAL | 2019-07-26T06:22:13.413645+00:00 | 2019-07-26T06:22:13.413676+00:00 | 338 | false | ```\n s = []\n for i,t in enumerate(text):\n if t not in s:\n while s and ord(t) <= ord(s[-1]) and s[-1] in text[i+1:]:\n s.pop()\n s.append(t)\n \n return \'\'.join(s)\n``` | 3 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | An TLE backtrack solution | an-tle-backtrack-solution-by-unclemario-e4w2 | Brute force solution with backtrack, spent an hour on this solution back in contest, finally did not worked out.\nThe algorithm works well except time complexit | unclemario | NORMAL | 2019-06-09T19:58:18.955522+00:00 | 2019-06-09T20:00:45.932708+00:00 | 167 | false | Brute force solution with backtrack, spent an hour on this solution back in contest, finally did not worked out.\nThe algorithm works well except time complexity is too high when input is long.\nAround half of cases passed.\nPut here to provide another idea.\n```\n\tString rst = "zzzzzzzzzzzzzzzzzzzzzzz";\n\n\tpublic String smallestSubsequence(String text) {\n\t\tMap<Character, Integer> chars = new HashMap<>();\n\t\tchar[] t = text.toCharArray();\n\t\tfor (char c : t) {\n\t\t\tint freq = chars.getOrDefault(c, 0);\n\t\t\tchars.put(c, freq + 1);\n\t\t}\n\t\tbacktrack(t, 0, chars, "");\n\t\treturn rst;\n\t}\n\n\tvoid backtrack(char[] t, int start, Map<Character, Integer> chars, String curt) {\n\t\tif (curt.length() == chars.size()) {\n\t\t\trst = rst.compareTo(curt) > 0 ? curt : rst;\n\t\t\treturn;\n\t\t}\n\t\tfor (int i = start; i < t.length; ++i) {\n\t\t\tint freq = chars.get(t[i]);\n\t\t\tString next = curt + t[i];\n\t\t\tif (freq > 0 && next.compareTo(rst) < 0) {\n\t\t\t\tchars.put(t[i], -1);\n\t\t\t\tbacktrack(t, i + 1, chars, curt + t[i]);\n\t\t\t\tchars.put(t[i], freq);\n\t\t\t}\n\t\t}\n\t}\n``` | 3 | 1 | [] | 0 |
smallest-subsequence-of-distinct-characters | Smallest Subsequence of Distinct Characters | smallest-subsequence-of-distinct-charact-easl | Complexity
Time complexity: O(N)
Space complexity: O(1)
Code | Ansh1707 | NORMAL | 2025-04-06T21:54:17.359557+00:00 | 2025-04-06T21:54:17.359557+00:00 | 15 | false |
# Complexity
- Time complexity: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python []
class Solution(object):
def smallestSubsequence(self, s):
"""
:type s: str
:rtype: str
"""
last_index = {c: i for i, c in enumerate(s)}
stack = []
seen = set()
for i, c in enumerate(s):
if c in seen:
continue
while stack and c < stack[-1] and i < last_index[stack[-1]]:
seen.remove(stack.pop())
stack.append(c)
seen.add(c)
return "".join(stack)
``` | 2 | 0 | ['String', 'Stack', 'Greedy', 'Monotonic Stack', 'Python'] | 0 |
smallest-subsequence-of-distinct-characters | Problem BreakDown || Intuition Explained || Java | problem-breakdown-intuition-explained-ja-5x27 | Similar solution on 316 leetcodeProblem BreakdownWhat is Lexicographically Smaller ?A string a is lexicographically smaller than a string b if in the first posi | dsuryaprakash89 | NORMAL | 2025-03-27T23:44:01.017462+00:00 | 2025-03-27T23:44:01.017462+00:00 | 59 | false | ## Similar solution on [316 leetcode](https://leetcode.com/problems/remove-duplicate-letters/solutions/6587779/problem-breakdown-intuition-explined-ja-wwdy/)
# Problem Breakdown
#### What is Lexicographically Smaller ?
A string `a` is lexicographically smaller than a string b if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`.
If the first `min(a.length, b.length)` characters do not differ, then the shorter string is the lexicographically smaller one.
##### Example
Starting with **c**
"**cba**c**d**cbc" = "cbad"
"**c**b**a**c**d**c**b**c" = "cadb"
Starting with **b**
"c**bacd**cbc" = "bacd"
"c**ba**c**dc**bc" = "badc"
"c**ba**c**d**cb**c**" = "badc" duplicate result
Starting with **a**
"cb**acd**c**b**c" = "acdb"
"cb**a**c**dcb**c" = "adcb"
"cb**a**c**d**c**bc**" = "adbc"
and once we arrange them lexicographically...
"acdb"
"adbc"
"adcb"
"bacd"
"badc"
"badc"
"cadb"
This is the Problem statement actually.
# Intuition
What we need to take care of ?
- We should check whether a character is in the stack or not - Boolean array is efficient than hashset in this scenario.
- Every element should occur once so on a long run check if current char is available later or not (in lexicographical ordering currently we may remove it but may not get later) - int array
- Comparing adjacent character - stack
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
- Initialise a stack to store the characters lexicographically
- Initialise an int array vis to keep track of last available index of a character
- Initialise a boolean array to check if a current char is in stack or not
- Iterate over the string
- update the vis array
- Iterate over the string
- if it is already in stack continue;
- While stack is not empty AND top of stack is more than the current element and is available in future
- pop it from stack
- mark it as unvisited
- push the char to stack
- mark it as visited
- Construct a stringBuilder sb
- pop all the chars and append to the string
- reverse the string and return it
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: $$O(n)$$ where `n` is length of the string
- For computing last array - $$O(n)$$
- Iterating over string and storing in stack - $$O(n)$$
- Building String - $$O(26)$$ at max it would store 26 characters
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
- Stack st at maximum stores 26 characters $$O(26)$$ ~ $$O(1)$$
- int last array is of $$O(26)$$ ~ $$O(1)$$
- boolean vis array is of $$O(26)$$ ~ $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public String removeDuplicateLetters(String s) {
Stack<Character> st = new Stack<>();
int [] last = new int[26];
boolean [] vis = new boolean[26];
for(int i=0;i<s.length();i++){
last[s.charAt(i)-'a']=i;
}
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(vis[c-'a']==true)continue;
while(!st.isEmpty()&&st.peek()>c&&last[st.peek()-'a']>i){
vis[st.pop()-'a']=false;
}
st.push(c);
vis[c-'a']=true;
}
StringBuilder sb= new StringBuilder();
while(!st.isEmpty()){
sb.append(st.pop());
}
return sb.reverse().toString();
}
}
``` | 2 | 0 | ['String', 'Stack', 'Greedy', 'Monotonic Stack', 'Java'] | 0 |
smallest-subsequence-of-distinct-characters | 🚀 Optimized Solution - Smallest Subsequence of Distinct Characters (Beats 100% in All Languages) | optimized-solution-smallest-subsequence-1x2bc | IntuitionThe goal is to find the smallest lexicographical order string by removing duplicate letters while maintaining the relative order of characters.
To achi | Harshit___at___work | NORMAL | 2025-03-02T05:58:28.711507+00:00 | 2025-03-02T05:59:11.612327+00:00 | 174 | false | # Intuition
The goal is to find the smallest lexicographical order string by removing duplicate letters while maintaining the relative order of characters.
To achieve this, we use a **monotonic stack** approach to ensure that the resultant string is in sorted order and contains only unique letters.
# Approach
1. **Frequency Count:** Maintain a frequency array `freq` to count occurrences of each character.
2. **Visited Set:** Use a boolean array `vis` (or a set in Python) to track which characters are already in the result.
3. **Monotonic Stack:**
- Iterate over the string.
- If the current character is already in the result (`vis` is true), decrement its frequency and continue.
- Otherwise, check the top of the stack:
- If the top character is **greater than the current character** and **it appears later in the string (freq > 0)**, remove it from the stack.
- Mark the removed character as unvisited.
- Push the current character onto the stack and mark it as visited.
4. **Result Construction:**
- Pop elements from the stack to construct the final answer in the correct order.
# Complexity
- **Time Complexity:**
- $$O(n)$$ (Each character is pushed and popped from the stack at most once.)
- **Space Complexity:**
- $$O(1)$$ (We use fixed-size arrays for `freq` and `vis`, and the stack holds at most 26 characters.)
---
# Code Implementations
```cpp []
class Solution {
public:
string smallestSubsequence(string s) {
vector<int> freq(26, 0);
vector<bool> vis(26, false);
stack<char> st;
for (char i : s) freq[i - 'a']++;
for (char i : s) {
if (vis[i - 'a']) {
freq[i - 'a']--;
continue;
}
while (!st.empty() && st.top() > i && freq[st.top() - 'a'] > 0) {
vis[st.top() - 'a'] = false;
st.pop();
}
st.push(i);
vis[i - 'a'] = true;
freq[i - 'a']--;
}
string ans = "";
while (!st.empty()) {
ans = st.top() + ans;
st.pop();
}
return ans;
}
};
```
```Java []
import java.util.*;
class Solution {
public String smallestSubsequence(String s) {
int[] freq = new int[26];
boolean[] vis = new boolean[26];
Stack<Character> stack = new Stack<>();
for (char ch : s.toCharArray()) freq[ch - 'a']++;
for (char ch : s.toCharArray()) {
freq[ch - 'a']--;
if (vis[ch - 'a']) continue;
while (!stack.isEmpty() && stack.peek() > ch && freq[stack.peek() - 'a'] > 0) {
vis[stack.pop() - 'a'] = false;
}
stack.push(ch);
vis[ch - 'a'] = true;
}
StringBuilder ans = new StringBuilder();
while (!stack.isEmpty()) {
ans.insert(0, stack.pop());
}
return ans.toString();
}
}
```
```Python []
class Solution:
def smallestSubsequence(self, s: str) -> str:
freq = {ch: 0 for ch in s}
vis = set()
stack = []
for ch in s:
freq[ch] += 1
for ch in s:
freq[ch] -= 1
if ch in vis:
continue
while stack and stack[-1] > ch and freq[stack[-1]] > 0:
vis.remove(stack.pop())
stack.append(ch)
vis.add(ch)
return "".join(stack)
```
| 2 | 0 | ['Hash Table', 'String', 'Stack', 'C++', 'Java', 'Python3'] | 0 |
smallest-subsequence-of-distinct-characters | Beginner Friendly Simple C++ Code | beginner-friendly-simple-c-code-by-mabdu-gdru | IntuitionTo find the lexicographically smallest subsequence of a string that contains all the distinct characters exactly once, we need to ensure two things:We | mAbdullah6829 | NORMAL | 2024-12-16T17:43:18.930404+00:00 | 2024-12-16T17:43:18.930404+00:00 | 245 | false | # Intuition\nTo find the lexicographically smallest subsequence of a string that contains all the distinct characters exactly once, we need to ensure two things:\n\nWe must include every distinct character in the resulting subsequence.\nThe sequence must be in lexicographical order. To achieve this, we need to track the remaining occurrences of each character and maintain the order by using a stack data structure to help with the sequence formation.\n\n# Approach\nFrequency Count: Count the frequency of each character in the input string s.\nStack for Result: Use a stack to build the resulting subsequence.\nInclusion Tracking: Use an array to track if a character is already included in the current result.\nIterate through the String: For each character, do the following:\nDecrease its count in the frequency array.\nIf the character is already in the stack, skip it.\nIf the character is not in the stack, ensure the stack remains lexicographically smallest by popping elements from the stack that are greater than the current character and can appear later in the string.\nPush the current character onto the stack and mark it as included.\nConstruct the Result: Convert the stack to a string to get the final result.\n# Complexity\n- Time complexity:\nO(n), where n is the length of the string. We process each character in the string once.\n\n- Space complexity:\nO(1), since the size of the frequency and inclusion arrays are fixed at 26 (for the 26 lowercase English letters), and the stack will hold at most 26 characters.\n# Code\n```cpp []\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n // Frequency count of each character\n int freq[26] = {0};\n for (char c : s) {\n freq[c - \'a\']++;\n }\n\n // Stack to store the result characters\n stack<char> st;\n // Boolean array to check if a character is in the current result\n bool inStack[26] = {false};\n \n for (char c : s) {\n // Decrement the frequency of the current character\n freq[c - \'a\']--;\n\n // If character is already in stack, skip it\n if (inStack[c - \'a\']) {\n continue;\n }\n\n // Ensure the stack remains lexicographically smallest\n while (!st.empty() && st.top() > c && freq[st.top() - \'a\'] > 0) {\n inStack[st.top() - \'a\'] = false;\n st.pop();\n }\n\n // Push current character onto the stack\n st.push(c);\n inStack[c - \'a\'] = true;\n }\n\n // Convert the stack to a string and return\n string result;\n while (!st.empty()) {\n result = st.top() + result;\n st.pop();\n }\n\n return result;\n }\n\n\n};\n``` | 2 | 0 | ['C++'] | 0 |
smallest-subsequence-of-distinct-characters | EASY||4 STEPS DETAIL APPROACH || SAME AS 316 | easy4-steps-detail-approach-same-as-316-j982h | Intuition\n Describe your first thoughts on how to solve this problem. \nWe can come up with the idea that for lexicographic we need a stack maybe but here the | Abhishekkant135 | NORMAL | 2024-01-10T04:15:47.442182+00:00 | 2024-03-07T05:11:13.475289+00:00 | 512 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can come up with the idea that for lexicographic we need a stack maybe but here the problem arises in removing , how do you know that the elements you are removing from stack are present later in string , might be the case that they are not present later. Also , considering the thing that it should not occur more than once , for this we will use a array and not a hashmap as it gets size extensive as we are looking up for alphabets and they are limited from 0 to 25 in the array only. \nWe will make a array which will initially store -1, later we upvate it with last occurence of the array indexed alphabets. So that while you remove from the stack you know if it is later present also or not.\n# LOOK FOR 1081 ON LEETCODE , THIS CODE THERE AS WELL WITHOUT MAKING ANY CHANGES.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialization:\n\nvisit[]: Array to track visited characters (0 for unvisited, 1 for visited).\nlastOccurence[]: Array to store the last occurrence index of each character.\nst: A stack to maintain the current result string in reverse order.\n2. Record Last Occurrences:\n\nIterate through s and store the last occurrence index of each character in lastOccurence[].\n3. Process Characters:\n\nIterate through s again:\nFor each character letter:\nWhile the stack is not empty, the top character is lexicographically greater than letter, and letter has a later occurrence:\nPop the top character from the stack (it\'s safe to remove).\nMark it as unvisited in visit[].\nIf letter hasn\'t been visited yet:\nPush it onto the stack.\nMark it as visited in visit[].\n4. Build Result:\n\nReverse the stack\'s contents to get the correct order and construct the result string.\nReturn Result:\n\n# Return the constructed string.UPVOTE\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nLINEAR\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nCONST.\n# Code\n```\nclass Solution {\n public String smallestSubsequence(String s) {\n int visit[]=new int [26];\n int lastOccurence []=new int [26];\n Stack <Character> st=new Stack<>();\n for(int i=0;i<26;i++){\n lastOccurence [i]=-1;\n }\n for(int i=0;i<s.length();i++){\n lastOccurence[s.charAt(i)-\'a\']=i;\n }\n for(int i=0;i<s.length();i++){\n char letter=s.charAt(i);\n while(!st.isEmpty() && st.peek()>letter && lastOccurence[st.peek()-\'a\']>i && visit[letter-\'a\']==0){\n visit[st.peek()-\'a\']=0;\n st.pop();\n }\n if(visit[letter-\'a\']==0){\n st.push(letter);\n visit[letter-\'a\']=1;\n }\n }\n StringBuilder ans=new StringBuilder("");\n while(!st.isEmpty()){\n ans.append(st.pop());\n }\n String originalString = ans.toString();\n return reverseString(originalString);\n }\n private static String reverseString(String str) {\n return new StringBuilder(str).reverse().toString();\n }\n}\n\n``` | 2 | 0 | ['Stack', 'Java'] | 2 |
smallest-subsequence-of-distinct-characters | Beats 99.33% 🔥|| Simple and Easy Approach Using string | beats-9933-simple-and-easy-approach-usin-qqjs | \n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to find the lexicographically smallest subsequence of distinct char | rahulstrive | NORMAL | 2024-01-01T11:15:16.400896+00:00 | 2024-01-01T11:15:16.400928+00:00 | 506 | false | \n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to find the lexicographically smallest subsequence of distinct characters\n that appears in the same order as the original string.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe use a greedy approach and a string to build the smallest subsequence.\n \n- We iterate through the characters in the original string.\n- If a character is already seen or has been added to the result, we skip it.\n- We remove characters from the end of the result if they are greater than the current character,\nhave remaining occurrences in the original string, and haven\'t been added to the result yet.\nWe add the current character to the result.\n\n# Complexity\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity :\nO(n) where n is the length of the input string\n\nSpace complexity:\n We use two arrays of size 26 (constant size), which contributes to O(26) or O(1) space.\nAdditionally, we use a StringBuilder to store the result, which can have a maximum length of n.\nTherefore, the overall space complexity is O(1 + n), which simplifies to O(n).\n\nNote: we can do this using stack also\n\n\n# Code\n```\nclass Solution {\n public String smallestSubsequence(String s) {\n int n = s.length();\n boolean[] seen = new boolean[26];\n int[] frq = new int[26];\n\n for (int i = 0; i < n; i++)\n frq[s.charAt(i) - \'a\']++;\n\n StringBuilder sb = new StringBuilder();\n\n for (int i = 0; i < n; i++) {\n char c = s.charAt(i);\n frq[c - \'a\']--;\n\n if (seen[c - \'a\'])\n continue;\n\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) > c && frq[sb.charAt(sb.length() - 1) - \'a\'] != 0) {\n seen[sb.charAt(sb.length() - 1) - \'a\'] = false;\n sb.deleteCharAt(sb.length() - 1);\n }\n\n sb.append(c);\n seen[c - \'a\'] = true;\n }\n\n return sb.toString();\n }\n}\n\n``` | 2 | 0 | ['String', 'Monotonic Stack', 'Java'] | 0 |
smallest-subsequence-of-distinct-characters | Solution with using map and set | solution-with-using-map-and-set-by-anime-t9to | \n\n# Code\n\nclass Solution {\n public String smallestSubsequence(String s) {\n Map<Character,Integer> map = new HashMap<>();\n for(int i = 0; | animesh23 | NORMAL | 2023-10-07T02:58:58.571381+00:00 | 2023-10-07T02:58:58.571409+00:00 | 986 | false | \n\n# Code\n```\nclass Solution {\n public String smallestSubsequence(String s) {\n Map<Character,Integer> map = new HashMap<>();\n for(int i = 0;i < s.length();i++){\n map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0) + 1);\n }\n Set<Character> set = new HashSet<>();\n Stack<Character> stack = new Stack<>();\n for(int i = 0;i < s.length();i++){\n if(!set.contains(s.charAt(i))){\n while(!stack.isEmpty() && stack.peek() > s.charAt(i) && map.containsKey(stack.peek())){\n set.remove(stack.pop());\n }\n set.add(s.charAt(i));\n stack.push(s.charAt(i));\n }\n if(map.get(s.charAt(i)) == 1){\n map.remove(s.charAt(i));\n }else{\n map.put(s.charAt(i),map.get(s.charAt(i)) - 1);\n }\n }\n StringBuilder sb = new StringBuilder();\n while(!stack.isEmpty()){\n sb.insert(0,stack.pop());\n }\n return String.valueOf(sb);\n }\n}\n``` | 2 | 0 | ['Hash Table', 'Stack', 'Monotonic Stack', 'Java'] | 0 |
smallest-subsequence-of-distinct-characters | Easy - Beginner Friendly || Stack || Hashmap || Monotonic Stack || Greedy || C++ | easy-beginner-friendly-stack-hashmap-mon-coqg | Code\ncpp\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n unordered_map<char,int>last;\n unordered_map<char,bool>taken;\n | kushagra_2k24 | NORMAL | 2023-09-26T04:14:48.760477+00:00 | 2023-09-26T04:14:48.760504+00:00 | 722 | false | # Code\n```cpp\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n unordered_map<char,int>last;\n unordered_map<char,bool>taken;\n stack<char>st;\n string ans="";\n for(int i=0;i<s.size();i++)\n last[s[i]]=i;\n for(int i=0;i<s.size();i++)\n {\n if(taken.find(s[i])!=taken.end())\n continue;\n while(st.size()!=0 && s[i]<st.top() && last[st.top()]>i)\n {\n taken.erase(st.top());\n st.pop();\n }\n taken[s[i]]=true;\n st.push(s[i]);\n }\n while(st.size()>0)\n {\n ans=st.top()+ans;\n st.pop();\n }\n return ans; \n }\n};\n``` | 2 | 0 | ['Hash Table', 'String', 'Stack', 'Greedy', 'Monotonic Stack', 'C++'] | 1 |
smallest-subsequence-of-distinct-characters | C++ || Monotonic Stack || Easy Solution | c-monotonic-stack-easy-solution-by-saif2-i6l5 | \n\n# Complexity\n- Time complexity:O(n)\n\n- Space complexity: O(n)\n\n# Code\n\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n | saif25 | NORMAL | 2023-07-09T15:28:27.747198+00:00 | 2023-07-09T15:28:27.747215+00:00 | 642 | false | \n\n# Complexity\n- Time complexity:O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n vector<int> vis(26,0);\n unordered_map<char,int> mp;\n for(auto ch : s) mp[ch]++;\n string ans="";\n for(int i=0;i<s.size();i++){\n mp[s[i]]--;\n if(vis[s[i]-\'a\']) continue;\n else{\n while(!ans.empty() && ans.back()>s[i] && mp[ans.back()]){\n vis[ans.back()-\'a\']=0;\n ans.pop_back();\n }\n ans.push_back(s[i]);\n vis[s[i]-\'a\']=1;\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['String', 'Monotonic Stack', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | JAVA Solution | Stack | java-solution-stack-by-sourin_bruh-nswk | Please upvote this solution as well as this :D\n\nclass Solution {\n public String smallestSubsequence(String s) {\n int n = s.length();\n bool | sourin_bruh | NORMAL | 2022-10-10T18:27:56.667204+00:00 | 2022-10-10T18:29:55.004254+00:00 | 416 | false | ### Please upvote this solution as well as *[this](https://leetcode.com/problems/remove-duplicate-letters/discuss/2687478/JAVA-Solution-or-Stack)* :D\n```\nclass Solution {\n public String smallestSubsequence(String s) {\n int n = s.length();\n boolean[] visited = new boolean[26];\n int[] lastIndex = new int[26];\n\n for (int i = 0; i < n; i++) {\n lastIndex[s.charAt(i) - \'a\'] = i;\n }\n\n Stack<Integer> stack = new Stack<>();\n\n for (int i = 0; i < n; i++) {\n int c = s.charAt(i) - \'a\';\n\n if(visited[c]) continue;\n visited[c] = true;\n\n while (!stack.isEmpty() && stack.peek() > c && lastIndex[stack.peek()] > i) {\n visited[stack.pop()] = false;\n }\n\n stack.push(c);\n }\n\n StringBuilder ans = new StringBuilder();\n\n for (Integer i : stack) {\n ans.append((char)(i + \'a\'));\n }\n\n return ans.toString();\n }\n}\n\n// TC: O(n), SC: O(n)\n``` | 2 | 0 | ['Stack', 'Java'] | 0 |
smallest-subsequence-of-distinct-characters | Easy Python solution in O(n) Time Complexity | easy-python-solution-in-on-time-complexi-fp0d | \nclass Solution:\n def smallestSubsequence(self, s: str) -> str:\n s=list(s)\n d={}\n for i in range(len(s)):\n d[s[i]]=i\n | aastha1916 | NORMAL | 2022-10-04T06:53:06.669179+00:00 | 2022-10-04T06:53:06.669225+00:00 | 516 | false | ```\nclass Solution:\n def smallestSubsequence(self, s: str) -> str:\n s=list(s)\n d={}\n for i in range(len(s)):\n d[s[i]]=i\n stack=[]\n for i in range(len(s)):\n if s[i] in stack:\n continue\n while len(stack)!=0 and d[stack[-1]]>i and stack[-1]>s[i]:\n stack.pop()\n stack.append(s[i])\n return(("").join(stack))\n \n \n \n``` | 2 | 0 | ['Stack', 'Python'] | 1 |
smallest-subsequence-of-distinct-characters | 100% FASTER 99.97% SPACE EFFICIENT EXPLAINED!!! | 100-faster-9997-space-efficient-explaine-x7zi | PLS UPVOTE if you like the SOLUTION:)\n\nTHE QUESTION IS exactly same as REMOVE DUPLICATE LETTERS so you can try it also:)\n\nIDEA:-\n\n We use a STACK in the f | Ryuga8150 | NORMAL | 2022-09-08T19:11:58.485556+00:00 | 2022-09-08T19:11:58.485626+00:00 | 405 | false | **PLS UPVOTE if you like the SOLUTION:)**\n\nTHE QUESTION IS exactly same as REMOVE DUPLICATE LETTERS so you can try it also:)\n\n**IDEA:-**\n\n* We use a STACK in the form of a string for this problem.\n* Also we use a vector of bool vec whose purpose is to determine which distinct elements are present in the stack currently and this vector is initialised with false.\n* WE also use another vector of int last that stores the last occurence of the corresponding characters.\n\n**DIVING INTO THE CODE.**\n\n* So, first loop is to set up our last vector.\n* Then another for loop is the main loop.\n* IF the stack is empty we simply push the element into the stack and mark it in the vec.\n* If the current element is not present in our stack then we check our top element of the stack(i.e the last element for the string that is acting as the stack) whether its greater than the current element that we are processing right now and further we need to satisfy one condition that if its greater then we need to pop but that element to be popped should appear later also and thats where our last vector comes in.\n* So, by using that if it satisfies that there is an occurence of that element later also then we pop.\n* IF the element is not greater now then we need to push the element and mark it in the vec as well.\n* NOW you can take a look at the code to understand completely:)\n\n**T.C:-** O(N) **S.C:-** O(N)\n\n```\nclass Solution {\npublic:\n string removeDuplicateLetters(string s) {\n string st;\n vector<bool>vec(26,0);\n vector<int>last(26,0);\n for(int i{0};i<s.length();++i){\n last.at(s[i]-\'a\')=i;\n }\n for(int i{0};i<s.length();++i){\n if(st.length()==0){\n st.push_back(s[i]);\n vec.at(s[i]-\'a\')=1;\n }else if(vec.at(s[i]-\'a\')==0){\n while(st.length() && st.back()>s[i]){\n if(last.at(st.back()-\'a\')>i){\n vec.at(st.back()-\'a\')=0;\n st.pop_back();\n }else{\n break;\n }\n }\n st.push_back(s[i]);\n vec.at(s[i]-\'a\')=1;\n }\n }\n return st; \n }\n};\n``` | 2 | 0 | ['String', 'Stack', 'C'] | 0 |
smallest-subsequence-of-distinct-characters | Simple Python Solution || beats 98% | simple-python-solution-beats-98-by-b1601-9zio | \nclass Solution:\n def smallestSubsequence(self, s: str) -> str:\n stack, seen = [], set()\n last = {c:idx for idx,c in enumerate(s)}\n | b160106 | NORMAL | 2022-09-01T10:25:09.945117+00:00 | 2022-09-01T10:25:09.945157+00:00 | 292 | false | ```\nclass Solution:\n def smallestSubsequence(self, s: str) -> str:\n stack, seen = [], set()\n last = {c:idx for idx,c in enumerate(s)}\n for idx, char in enumerate(s):\n if char in seen:\n continue\n while stack and stack[-1] > char and idx < last[stack[-1]]:\n c = stack.pop()\n seen.remove(c)\n stack.append(char)\n seen.add(char)\n return "".join(stack)\n\n``` | 2 | 0 | ['Python'] | 0 |
smallest-subsequence-of-distinct-characters | ✅✅Faster || Easy To Understand || C++ Code | faster-easy-to-understand-c-code-by-__kr-g1zk | Using Stack && Unordered Map\n\n Time Complexity :- O(N)\n\n Space Complexity :- O(N)\n\n\nclass Solution {\npublic:\n string smallestSubsequence(string str) | __KR_SHANU_IITG | NORMAL | 2022-08-05T09:51:45.314341+00:00 | 2022-08-05T09:51:45.314382+00:00 | 242 | false | * ***Using Stack && Unordered Map***\n\n* ***Time Complexity :- O(N)***\n\n* ***Space Complexity :- O(N)***\n\n```\nclass Solution {\npublic:\n string smallestSubsequence(string str) {\n \n int n = str.size();\n \n // count store the frequency of element\n \n vector<int> count(26, 0);\n \n // vis keeps track of included element\n \n vector<bool> vis(26, false);\n \n // store the frequency of each element\n \n for(int i = 0; i < n; i++)\n {\n count[str[i] - \'a\']++;\n }\n \n // stack will store the character in increasing order\n \n stack<char> st;\n \n for(int i = 0; i < n; i++)\n {\n // decrement the frequency of curr character\n \n count[str[i] - \'a\']--;\n \n // if curr character is already included\n \n if(vis[str[i] - \'a\'])\n {\n continue;\n }\n else\n {\n // remove the greater character from stack\n \n while(!st.empty() && str[i] < st.top() && count[st.top() - \'a\'] > 0)\n {\n // mark not included\n \n vis[st.top() - \'a\'] = false;\n \n st.pop();\n }\n \n // push the current character in stack\n \n st.push(str[i]);\n \n // mark included\n \n vis[str[i] - \'a\'] = true;\n }\n }\n \n // take out the characters from stack\n \n string res = "";\n \n while(!st.empty())\n {\n res = st.top() + res;\n \n st.pop();\n }\n \n return res;\n }\n};\n``` | 2 | 0 | ['Stack', 'C', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | Python | Monotonic stack, Set, and Counter | python-monotonic-stack-set-and-counter-b-6myg | \nclass Solution:\n def smallestSubsequence(self, s: str) -> str:\n\t\t# count how many of each character we have available in `s`\n charCount = Count | sr_vrd | NORMAL | 2022-06-08T21:08:35.052317+00:00 | 2022-06-08T21:08:35.052344+00:00 | 591 | false | ```\nclass Solution:\n def smallestSubsequence(self, s: str) -> str:\n\t\t# count how many of each character we have available in `s`\n charCount = Counter(s)\n charsInStack, charStack = set(), []\n \n for i, char in enumerate(s):\n\t\t\t# if char is not currently in charStack, we remove as many characters as possible and place it at the top\n if char not in charsInStack:\n\t\t\t\t# we remove the top of the stack if there are more of that character coming up AND char is smaller lexicographically\n while charStack and char < charStack[-1] and charCount[charStack[-1]] > 0:\n charsInStack.remove(charStack.pop())\n\t\t\t\t# after removing as many characters as possible, we add char to the top of the stack\n charStack.append(char)\n\t\t\t\t# we use a set to keep track of what characters are in the stack to lookup in O(1) time\n charsInStack.add(char)\n charCount[char] -= 1\n\t\t\n\t\t# the resulting stack has every character from `s` exacyly once and in the best lexicographical position possible\n return "".join(charStack)\n``` | 2 | 0 | ['Monotonic Stack', 'Ordered Set', 'Python'] | 1 |
smallest-subsequence-of-distinct-characters | Without Stack | without-stack-by-shubhammishra115-0oy7 | \n\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n unordered_map<char, int> map;\n for (int i = 0; i < s.size(); i++)\n | shubhammishra115 | NORMAL | 2022-03-18T17:13:06.449206+00:00 | 2022-03-18T17:13:06.449238+00:00 | 213 | false | \n```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n unordered_map<char, int> map;\n for (int i = 0; i < s.size(); i++)\n map[s[i]]++;\n string ans = "";\n vector<bool> visited(26, false);\n for (int i = 0; i < s.size(); i++)\n {\n if (visited[s[i] - \'a\'])\n map[s[i]]--;\n while (ans.size() > 0 && visited[s[i] - \'a\'] == false && ans.back() >= s[i] && map[ans.back()] > 1)\n {\n visited[ans.back() - \'a\'] = false;\n map[ans.back()]--;\n ans.pop_back();\n }\n if (!visited[s[i] - \'a\'])\n {\n ans.push_back(s[i]);\n visited[s[i] - \'a\'] = true;\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | C++ || Code with Explanation || Why use Stack? | c-code-with-explanation-why-use-stack-by-l7b4 | Brief Overview:\nThe aim is to find the lexicographically shortest subsequence having distinct letters.\nThere would exist various permutations of subsequences | anuragkiitb | NORMAL | 2022-03-18T15:52:44.508041+00:00 | 2022-03-18T16:09:13.740606+00:00 | 113 | false | **Brief Overview:**\nThe aim is to find the lexicographically shortest subsequence having distinct letters.\nThere would exist various permutations of subsequences that would have distinct letters. For instance if the String is "bcabc" , following are the subsequences possible: { "bca" , "cab" , "bac" ,"abc" }, out of which lexicographically smallest is "abc" which is the answer.\n\n**How to Approach:**\n\n**Brute Force:**\nIn a Brute force Approach, we can use a Hashmap/Dictionary to map all the characters to all the indices and then generate all the possible subsequence permutations. Although this would give the correct answer, Computation would be very costly as generating and checking for every subsequence will take up factorial time complexity.\n\n**How to Optimize:**\nThe challenge is to think of a data structure or algorithm which can reduce the time complexity.\nFirst, we have to pick the characters if they are not already visited(to main distinctiveness). If that\'s the case, we\'ll try to pick these characters. We\'ll also make sure the previously picked character is smaller then the current character to maintain lexicographical order. To implement this we will use a **Stack!!**\nAs a general rule of thumb, a Stack data structure should be used to keep track of comparison among previously chosen/ next chosen elements.\n\n**How to Implement:**\nWe use the visited to keep track of selected characters.\nWe will loop through all characters of the string and take the following actions: \n* If the stack is empty, we\'ll put the current character into our stack.\n* We\'ll also keep here boolean array which will mark whether we have seen this character or not. So, if we are getting the same character again and we have already seen that. We\'ll ignore that character.\n* For every character, we will see if some greater characters are present in the stack, which can also be used later. As far as possible, we will make use of greater characters that are present farthest in the string. (How to do this is explained in the comments of the code).\n\n**Code (with comments) :**\n\n```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n int n=s.size();\n vector<bool> vis(26,0); // keeping track of visited letters\n vector<int> lastInd(26,-1); // The last occurence of letter in the string\n for(int i=0;i<n;i++){\n lastInd[s[i]-\'a\']=i;\n }\n stack<char> st; \n for(int i=0;i<n;i++){\n if(!vis[s[i]-\'a\']){\n vis[s[i]-\'a\']=1;\n // Checking only if letter not visited previously\n // Once we meet this condition we are sure to push \n // this character into the stack, before that \n // we will check stack\'s surrent status and check for \n // any elements that can be removed. \n while(!st.empty() && lastInd[st.top()-\'a\']>i && st.top()>s[i]){\n // If a greater letter is present again in the string \n //at a a later index,lets use that index to use this character\n // , so for now we keep it out of stack and make it unvisited \n // to be able to be used later.\n vis[st.top()-\'a\']=0;\n st.pop();\n }\n st.push(s[i]);\n }\n }\n string ans="";\n // Pour out all the stack contents into a string and reverse it.\n while(!st.empty()){\n char c=st.top();\n st.pop();\n ans+=c;\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n};\n```\n\n**Complexity Analysis :**\nTime: **O(N)** (one pass through the string every time, no nested loops)\nSpace: **O(N)** (lastInd array of size n, visited boolean array of size n, stack size)\n\nComment down below, If you have any queries or suggestions :)\nBest Wishes, \nAnurag | 2 | 0 | ['Stack'] | 0 |
smallest-subsequence-of-distinct-characters | java solution using stack with comments | java-solution-using-stack-with-comments-qsfvp | Detail can be found here->\nhttps://leetcode.com/problems/remove-duplicate-letters/discuss/1860486/java-solution-using-stack-with-comments\n\n\n public String s | kushguptacse | NORMAL | 2022-03-18T11:44:10.985546+00:00 | 2022-03-18T11:47:22.828499+00:00 | 525 | false | Detail can be found here->\nhttps://leetcode.com/problems/remove-duplicate-letters/discuss/1860486/java-solution-using-stack-with-comments\n\n```\n public String smallestSubsequence(String s) {\n\t\t// hold last index of every character.\n\t\tint[] lastIndex = new int[26];\n\t\t// visited array to store every char value.\n\t\tboolean[] visited = new boolean[26];\n\t\t// hold the answer sub sequence.\n\t\tDeque<Character> ansStack = new LinkedList<>();\n\t\t// prepare last index of every character\n\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\tlastIndex[s.charAt(i) - \'a\'] = i;\n\t\t}\n\t\t// iterate each char of String\n\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\tchar ch = s.charAt(i);\n\t\t\t// if current char already visited don\'t do anything\n\t\t\tif (visited[ch - \'a\']) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// check if top of stack > current char. and if that top element of stack is\n\t\t\t// repeating later.\n\t\t\twhile (!ansStack.isEmpty() && ansStack.peek() > ch && lastIndex[ansStack.peek() - \'a\'] > i) {\n\t\t\t\t// remove top element from stack as we have smaller lexicographic string\n\t\t\t\t// combination available.\n\t\t\t\t// also make visited of top element to false as we need to read it again latter\n\t\t\t\t// for placement.\n\t\t\t\tvisited[ansStack.pop() - \'a\'] = false;\n\t\t\t}\n\t\t\t// set visited of current char true and add curr char to answer stack\n\t\t\tvisited[ch - \'a\'] = true;\n\t\t\tansStack.push(ch);\n\t\t}\n\n\t\tStringBuilder sb = new StringBuilder();\n\t\t// now we need to get elements from stack and add it to the stringBuilder\n\t\twhile (!ansStack.isEmpty()) {\n\t\t\tsb.append(ansStack.pop());\n\t\t}\n\t\t// since element are in reverse order. just reverse the elements.\n\t\treturn sb.reverse().toString();\n\t}\n``` | 2 | 0 | ['Stack', 'Java'] | 0 |
smallest-subsequence-of-distinct-characters | Simple C++ Solution || 100% faster || | simple-c-solution-100-faster-by-vishwaje-b8ig | \n\nclass Solution {\n \npublic:\n \n string smallestSubsequence(string s) {\n \n vector<int> cand(256, 0);\n vector<bool> visited( | Vishwajeet_Pawar | NORMAL | 2022-03-18T05:59:04.619664+00:00 | 2022-03-18T05:59:04.619710+00:00 | 337 | false | ```\n\nclass Solution {\n \npublic:\n \n string smallestSubsequence(string s) {\n \n vector<int> cand(256, 0);\n vector<bool> visited(256, false);\n\n for(auto&k:s)\n cand[k]++ ;\n \n string res = "0" ;\n \n for(auto&k:s)\n {\n cand[k]-- ;\n if(visited[k])\n continue ;\n while( k < res.back() && cand[res.back()] )\n {\n visited[res.back()] = false ;\n res.pop_back() ;\n }\n res+=k ;\n visited[k] = true ;\n }\n \n return res.substr(1) ;\n }\n \n};\n``` | 2 | 0 | ['C', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | JS & TS simple solution using stack | js-ts-simple-solution-using-stack-by-jin-sswv | This solution is based on this solution.\n\n\nfunction smallestSubsequence(s: string): string {\n const stack = [];\n \n for (let i = 0; i < s.length; | JinZihang | NORMAL | 2022-03-18T03:37:49.278389+00:00 | 2022-03-18T03:37:49.278431+00:00 | 266 | false | This solution is based on [this solution](http://leetcode.com/problems/remove-duplicate-letters/discuss/977608/Use-stack-to-solve-by-JS-94.89-fast-100-less-memory-with-explaination).\n\n```\nfunction smallestSubsequence(s: string): string {\n const stack = [];\n \n for (let i = 0; i < s.length; i++) {\n const char = s[i];\n \n if (stack.indexOf(char) > -1) continue;\n \n while (stack.length > 0 \n && stack[stack.length - 1] > char \n && s.indexOf(stack[stack.length - 1], i) > i) stack.pop();\n \n stack.push(char);\n }\n \n return stack.join("");\n};\n``` | 2 | 0 | ['Stack', 'TypeScript', 'JavaScript'] | 0 |
smallest-subsequence-of-distinct-characters | Detailed explanation of logic with code | detailed-explanation-of-logic-with-code-lh3ux | The lexicographic part is the trouble maker in an otherwise simple problem.\nWe don\'t just want to remove the duplicates, but we want to remove duplicates in a | me_abhishek92 | NORMAL | 2021-12-08T09:45:05.649397+00:00 | 2021-12-08T09:45:05.649426+00:00 | 210 | false | The lexicographic part is the trouble maker in an otherwise simple problem.\nWe don\'t just want to remove the duplicates, but we want to remove duplicates in a manner that the resultant string is lexicographically smallest.\n\nLet\'s try to get to the solution using an example.\n\ns = "bcabc"\nHere we have 4 possible solutions: abc, bca, bac, cab. Out of these abc is smallest lexicographically.\n\n**Observations:**\n\n* We need a mechanism to know whether a certain character is going to appear later in the string. In our above example, At index 0, we have b. But we need to know whether b will appear again or not. If it appears again, then we can think of removing it. But if it does not appear again, then we have no choice but to keep this letter in our answer.\n* If current letter is lexicographically smaller than previous letters, AND the previous letters appear again later in array, we need to remove these previous letters from our answer, and add the current letter. Which data structure is best for keeping track of previous consecutive data? Stack!\n\n**Approach:**\n* To keep track of the highest index of each letter, we will use a Hashmap. So once we will go through the string and update our map. key will be the character, and value will be its index. Once the traversal is done, all characters will have highest indices updated in the map. (See first 5 lines code for clarity.)\n* We will use a stack to keep track of the letters, but we will also need a mechanism for checking whether a letter has already been added to the stack. (This point will become clear in a while)\n* We now go through the string, and do the following for each letter:\n1. Check if this letter is lexicographically smaller/bigger than the character at the top of the stack. If it is smaller, then we will **pop the stack only if the character at the top appears again later in the string**. Other wise just add it to the stack and the set iff this letter is not already added earlier (This is where the set comes in handy).\n2. Repeat the above step as long as current character is smaller than stack\'s top character.\n3. If the current character is bigger, then simply add this character to the stack and set if not already added before.\nGo through the code for better clarity.\n\nCode:\n```\nclass Solution {\n public String removeDuplicateLetters(String s) {\n HashMap<Character, Integer> countMap = new HashMap();\n for(int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n countMap.put(c,i);\n }\n \n Stack<Character> stack = new Stack();\n Set<Character> set = new HashSet();\n \n for(int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if(!set.contains(c)) {\n while(!stack.isEmpty() \n && c < stack.peek() \n && countMap.get(stack.peek()) >= i){\n set.remove(stack.pop());\n }\n stack.push(c);\n set.add(c);\n }\n }\n \n String ans = "";\n while(!stack.isEmpty()) {\n ans = stack.pop() + ans;\n }\n \n return ans;\n }\n}\n```\n\n\nHope this helps.\nPlease drop comments for any queries/suggestions.\nPeace! | 2 | 0 | ['Stack'] | 1 |
smallest-subsequence-of-distinct-characters | C++, 100% solution easy | c-100-solution-easy-by-abivilion-8f17 | \nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n vector<int> freq(26,0);\n for(char c : s){\n freq[c-\'a\']++; | abivilion | NORMAL | 2021-11-07T12:14:16.228025+00:00 | 2021-11-07T12:14:16.228050+00:00 | 355 | false | ```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n vector<int> freq(26,0);\n for(char c : s){\n freq[c-\'a\']++;\n }\n vector<int> visited(26, 0);\n \n string ret = "";\n \n for(int i = 0 ; i < s.length(); i++){\n \n freq[s[i]-\'a\']--;\n \n if(visited[s[i]-\'a\']) continue;\n \n while(ret.length() > 0 && freq[ret.back()-\'a\'] != 0 && ret.back() > s[i]){\n visited[ret.back()-\'a\'] = false;\n ret.pop_back();\n }\n \n ret.push_back(s[i]);\n \n visited[s[i]-\'a\'] = true;\n \n }\n \n return ret;\n \n }\n};\n``` | 2 | 0 | ['C', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | C++ solution || Greedy || Stack | c-solution-greedy-stack-by-ariyanlaskar-ib3y | \nstring smallestSubsequence(string s) {\n string ans="";\n map<char,bool>exists;\n map<char,int>freq;\n for(int i=0;i<s.length();i++ | Ariyanlaskar | NORMAL | 2021-08-25T05:13:35.981195+00:00 | 2021-08-25T05:13:35.981248+00:00 | 263 | false | ```\nstring smallestSubsequence(string s) {\n string ans="";\n map<char,bool>exists;\n map<char,int>freq;\n for(int i=0;i<s.length();i++){\n exists[s[i]]=false;\n freq[s[i]]++;\n }\n stack<char>st;\n st.push(s[0]);\n exists[s[0]]=true;\n \n for(int i=1;i<s.length();i++){\n if(s[i]<=st.top()){\n if(exists[s[i]]==false){\n while(!st.empty() && s[i]<st.top() && freq[st.top()]>1){\n freq[st.top()]--;\n exists[st.top()]=false;\n st.pop(); \n }\n st.push(s[i]);\n \n exists[s[i]]=true;\n }\n else{\n freq[s[i]]--;\n \n }\n }\n else{\n if(exists[s[i]]==false){\n st.push(s[i]);\n exists[s[i]]=true;\n \n }\n }\n \n }\n while(!st.empty()){\n ans.push_back(st.top());\n st.pop();\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n``` | 2 | 0 | ['Stack', 'Greedy'] | 0 |
smallest-subsequence-of-distinct-characters | 100% easy c++ | 100-easy-c-by-anurag05683-hi5c | \n# if you like this code please do upvote \nint n=s.length();\n\tvector frequency(26,0);`` // datatype = int\n vector visited(26,false); // data type | anurag05683 | NORMAL | 2021-08-10T18:54:38.397950+00:00 | 2021-08-10T18:58:17.024001+00:00 | 284 | false | \n# if you like this code please do upvote \nint n=s.length();\n\tvector<int> frequency(26,0);`` // datatype = int\n vector<int> visited(26,false); // data type = int \n stack<char> st; // char datatype\n \n for(int i=0;i<n;i++)\n frequency[s[i]-\'a\']++;\n \n for(auto a:s)\n {\n frequency[a-\'a\']--;\n if(visited[a-\'a\']==true) continue;\n \n while( !st.empty() && a< st.top() && frequency[st.top()-\'a\']>0 ) // if top of stack is greater then current character\n {\n \n visited[st.top()-\'a\']=false;\n st.pop();\n }\n \n st.push(a);\n visited[a-\'a\']=true;\n \n }\n \n string ans="";\n while( !st.empty())\n {\n ans.push_back(st.top()) ;\n st.pop();\n }\n \n reverse(ans.begin() , ans.end()) ;\n \n return ans; | 2 | 0 | ['Stack', 'C'] | 0 |
smallest-subsequence-of-distinct-characters | [JavaScript] 10 lines solution (100%,80%) | javascript-10-lines-solution-10080-by-05-1436 | Runtime: 72 ms, faster than 100.00% of JavaScript online submissions for Smallest Subsequence of Distinct Characters.\nMemory Usage: 39.4 MB, less than 80.00% o | 0533806 | NORMAL | 2021-05-28T09:31:26.003811+00:00 | 2021-05-28T09:33:25.989005+00:00 | 385 | false | Runtime: 72 ms, faster than 100.00% of JavaScript online submissions for Smallest Subsequence of Distinct Characters.\nMemory Usage: 39.4 MB, less than 80.00% of JavaScript online submissions for Smallest Subsequence of Distinct Characters.\n```\nvar smallestSubsequence = function(s) {\n let stack = [];\n for(let i = 0; i < s.length; i++){\n if(stack.includes(s[i])) continue;\n while(stack[stack.length-1]>s[i] && s.substring(i).includes(stack[stack.length-1])) stack.pop();\n stack.push(s[i]);\n }\n return stack.join("");\n};\n``` | 2 | 1 | ['JavaScript'] | 0 |
smallest-subsequence-of-distinct-characters | python STACK O(N) time complexity O(K) space complexity easy to read | python-stack-on-time-complexity-ok-space-8hgb | \ndef smallestSubsequence(self, chars: str) -> str:\n current_string_chars = set()\n stack = []\n hm = Counter(chars)\n\n for char i | GSWE | NORMAL | 2021-05-20T03:41:47.868551+00:00 | 2021-05-20T04:06:22.513718+00:00 | 111 | false | ```\ndef smallestSubsequence(self, chars: str) -> str:\n current_string_chars = set()\n stack = []\n hm = Counter(chars)\n\n for char in chars:\n while stack and char < stack[-1] and char not in current_string_chars and hm[stack[-1]] > 0:\n current_string_chars.remove(stack[-1])\n stack.pop()\n if char not in current_string_chars:\n stack.append(char)\n current_string_chars.add(char)\n hm[char] -= 1\n\n return "".join(stack)\n\n``` | 2 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | Easy C++ solution using Stack | easy-c-solution-using-stack-by-vaibhav27-hr7x | ```\nstring smallestSubsequence(string str) {\n int lastIndex[26] = {0};\n bool charUsed[26] = {false};\n \n stack s;\n \n | vaibhav277 | NORMAL | 2021-02-20T10:41:10.982807+00:00 | 2021-02-20T10:41:10.982841+00:00 | 185 | false | ```\nstring smallestSubsequence(string str) {\n int lastIndex[26] = {0};\n bool charUsed[26] = {false};\n \n stack<char> s;\n \n for(int i=0;i<str.size();i++){\n lastIndex[str[i]-\'a\'] = i;\n }\n \n for(int i=0;i<str.size();i++){\n char ch = str[i];\n if(!charUsed[ch-\'a\']){\n while(!s.empty() && s.top()>ch && lastIndex[s.top()-\'a\'] > i){\n charUsed[s.top()-\'a\'] = false;\n s.pop();\n }\n s.push(ch);\n charUsed[ch-\'a\'] = true;\n }\n }\n \n string ans;\n while(!s.empty()){\n ans += s.top();\n s.pop();\n }\n \n string finalans;\n finalans = ans;\n reverse(finalans.begin(),finalans.end());\n \n return finalans;\n } | 2 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | C++ 0ms O(n) using string as stack | c-0ms-on-using-string-as-stack-by-rishab-shoe | \nstring smallestSubsequence(string text) {\n if(text.length()==0)\n return text;\n vector<int> freq(26,0);\n for(char &ch : tex | rishabhsp98 | NORMAL | 2020-08-03T06:40:58.917632+00:00 | 2020-08-04T12:45:09.205744+00:00 | 343 | false | ``` \nstring smallestSubsequence(string text) {\n if(text.length()==0)\n return text;\n vector<int> freq(26,0);\n for(char &ch : text)\n freq[ch-\'a\']++;\n \n vector<bool> seen(26,0);\n string ans="0";\n for(char &ch: text)\n {\n freq[ch-\'a\']--;\n if(seen[ch-\'a\']==true) //we can not have duplicate char\n continue;\n while(ans.back() > ch && freq[ans.back()-\'a\'] >0) //We\'ll only pop when ans.back() char has freq >0 (means it cannot occur later in string so must preserve it because we have to have each letter in ans and distinct also)\n {\n seen[ans.back()-\'a\']=false; //as we\'are removing the last char so we mark it not vis in ans string\n ans.pop_back();\n }\n \n seen[ch-\'a\']=true;\n ans+=ch;\n }\n return ans.substr(1);\n }\n\n``` | 2 | 1 | ['C'] | 0 |
smallest-subsequence-of-distinct-characters | Java O(n) O(1) (beats 100%) | java-on-o1-beats-100-by-rohitvish3094-d4s4 | ```\n// Solution - Time Complexity O(n) and space complexity O(1) (Here we have used arrays of length 26 making it of constant space)\n \n //if le | rohitvish3094 | NORMAL | 2020-07-16T05:39:34.189839+00:00 | 2020-07-16T05:39:34.189876+00:00 | 261 | false | ```\n// Solution - Time Complexity O(n) and space complexity O(1) (Here we have used arrays of length 26 making it of constant space)\n \n //if length of the string is 1 or 0 return that string\n if(s.length()<=1)\n return s;\n \n int len=s.length();\n // This will hold our current unique element\n boolean[] seen=new boolean[26];\n \n // This will hold our every character\'s of string last index \n int[] lastOccurence=new int[26];\n \n // First add all the elements in the lastOccurence array with its last index\n for(int i=0;i<len;i++){\n lastOccurence[s.charAt(i)-\'a\']=i;\n }\n \n // This will hold our final string characters\n StringBuilder sb=new StringBuilder();\n \n // Now we will check for each character from the start\n for(int i=0;i<len;i++){\n char c=s.charAt(i);\n \n //if the current character is not seen in the seen array\n if(!seen[c-\'a\']){\n int currLen=sb.length();\n \n // loop till the current character is less than other elements in our already made final string provided they have to be seen later (this we will check through lastOccurence array for each character\'s last occuring index in the string)\n while(currLen>0 && c<sb.charAt(currLen-1) && lastOccurence[sb.charAt(currLen-1)-\'a\']>i){\n // if condition satisifes remove the other characters from our final string accordingly as if it is not seen yet \n // mark all to be removed characters as unseen\n seen[sb.charAt(currLen-1)-\'a\']=false;\n // remove that characters from our final string\n sb.deleteCharAt(currLen-1);\n //set the new length of our final string\n currLen=sb.length();\n }\n //append the current character\n sb.append(c);\n // marked it as seen\n seen[c-\'a\']=true;\n }\n \n }\n \n return sb.toString();\n | 2 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | [PYTHON 3] Stacks | Dictionary | Easy to Read Solution | python-3-stacks-dictionary-easy-to-read-x4156 | \nclass Solution:\n def smallestSubsequence(self, text: str) -> str:\n stack , counter , visited = [] , {} , {}\n for letter in text:\n | mohamedimranps | NORMAL | 2020-06-14T16:33:43.617645+00:00 | 2020-06-14T16:33:43.617674+00:00 | 600 | false | ```\nclass Solution:\n def smallestSubsequence(self, text: str) -> str:\n stack , counter , visited = [] , {} , {}\n for letter in text:\n if letter not in visited:\n visited[letter] = False\n counter[letter] = 1\n else:\n counter[letter] += 1\n for letter in text:\n counter[letter] -= 1\n if visited[letter]:\n continue\n while stack and letter < stack[-1] and counter[stack[-1]] > 0:\n visited[stack[-1]] = False\n stack.pop()\n stack.append(letter)\n visited[letter] = True\n return "".join(stack)\n``` | 2 | 0 | ['Python3'] | 0 |
smallest-subsequence-of-distinct-characters | Python Solution w/ Counter and Stack | python-solution-w-counter-and-stack-by-s-hckm | \nclass Solution:\n def smallestSubsequence(self, text: str) -> str:\n count = Counter(text); visited = {}; st = [] # stack\n \n for cu | seank | NORMAL | 2020-05-31T04:54:52.239285+00:00 | 2020-05-31T04:54:52.239317+00:00 | 207 | false | ```\nclass Solution:\n def smallestSubsequence(self, text: str) -> str:\n count = Counter(text); visited = {}; st = [] # stack\n \n for curr in text:\n count[curr] -= 1\n if curr in visited and visited[curr]: continue\n \n while st:\n prev = st[-1]\n if curr >= prev or count[prev] <= 0: break\n st.pop(); visited[prev] = False\n \n st.append(curr); visited[curr] = True\n \n return "".join(st)\n```\t\t | 2 | 0 | [] | 1 |
smallest-subsequence-of-distinct-characters | C++ | Hash-map | Clean and readable | c-hash-map-clean-and-readable-by-wh0ami-lfbc | Intuition:\n1) Store frequency of characters.\n2) Start making a resultant string where in if we see that incoming character is smaller than the already added l | wh0ami | NORMAL | 2020-05-20T18:27:07.799188+00:00 | 2020-05-21T09:01:33.636923+00:00 | 236 | false | **Intuition:**\n1) Store frequency of characters.\n2) Start making a resultant string where in if we see that incoming character is smaller than the already added last one then we pop the last character in resultant string if there we can get them later.\n\n```\nclass Solution {\npublic:\n string smallestSubsequence(string text) {\n int n = text.length();\n \n unordered_map<char, int>hm;\n for (int i = 0; i < n; i++)\n hm[text[i]]++;\n \n unordered_map<char, bool>seen;\n string res;\n \n for (int i = 0; i < n; i++) {\n hm[text[i]]--;\n if (seen[text[i]]) continue;\n seen[text[i]] = true;\n \n while(!res.empty() && res.back() > text[i] && hm[res.back()] > 0) {\n seen[res.back()] = false;\n res.pop_back();\n }\n \n res.push_back(text[i]);\n }\n \n return res;\n }\n};\n``` | 2 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | C++ Concise 100% | c-concise-100-by-ritikmishra-2l7v | class Solution {\npublic:\n string smallestSubsequence(string text) {\n \n string str="";\n vector count(26,0);\n vector used(26, | ritikmishra | NORMAL | 2020-04-25T10:44:10.098975+00:00 | 2020-04-25T10:44:10.099028+00:00 | 435 | false | class Solution {\npublic:\n string smallestSubsequence(string text) {\n \n string str="";\n vector<int> count(26,0);\n vector<bool> used(26,false);\n for (auto i:text)\n count[i-\'a\']++;\n \n for (auto i:text)\n {\n count[i-\'a\']--;\n\n if(used[i-\'a\']==false)\n {\n\n while (str.length()>0 && i<str.back() && count[str.back()-\'a\']>0)\n {\n used[str.back()-\'a\']= false;\n str.pop_back();\n }\n\n str.push_back(i);\n used[i-\'a\']= true;\n }\n\n }\n\n return str;\n }\n}; | 2 | 0 | ['C', 'C++'] | 1 |
smallest-subsequence-of-distinct-characters | Easy Python Stack 100%-100% | easy-python-stack-100-100-by-rooch-j0n6 | python\nclass Solution:\n def smallestSubsequence(self, S):\n indexLast = {S[i]: i for i in range(len(S))}\n stack = []\n for i in range | rooch | NORMAL | 2020-04-02T15:57:58.312018+00:00 | 2020-04-02T15:57:58.312070+00:00 | 131 | false | ```python\nclass Solution:\n def smallestSubsequence(self, S):\n indexLast = {S[i]: i for i in range(len(S))}\n stack = []\n for i in range(len(S)):\n if S[i] in stack: continue\n\n while stack and stack[-1] > S[i] and i < indexLast[stack[-1]]:\n stack.pop()\n stack.append(S[i])\n \n return "".join(stack)\n``` | 2 | 1 | [] | 0 |
smallest-subsequence-of-distinct-characters | C++ 100% time and space solution | c-100-time-and-space-solution-by-jasperj-0ewj | \tclass Solution {\n\tpublic:\n\t\tstring smallestSubsequence(string text) {\n\t\t\tunordered_map m;\n\t\t\tfor(int i=0;i<text.size();i++){\n\t\t\t\tm[text[i]]= | jasperjoe | NORMAL | 2020-03-10T12:34:16.933183+00:00 | 2020-03-10T12:34:16.933216+00:00 | 433 | false | \tclass Solution {\n\tpublic:\n\t\tstring smallestSubsequence(string text) {\n\t\t\tunordered_map<char,int> m;\n\t\t\tfor(int i=0;i<text.size();i++){\n\t\t\t\tm[text[i]]=i;\n\t\t\t}\n\t\t\tstring ans;\n\t\t\tunordered_set<char> visited;\n\t\t\tfor(int i=0;i<text.size();i++){\n\t\t\t\twhile(!visited.count(text[i]) && !ans.empty() && text[i]<ans.back() && m[ans.back()]>i){\n\t\t\t\t\tvisited.erase(ans.back());\n\t\t\t\t\tans.pop_back();\n\t\t\t\t}\n\t\t\t\tif(!visited.count(text[i])){\n\t\t\t\t\tans+=text[i];\n\t\t\t\t\tvisited.insert(text[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ans; \n\t\t}\n\t}; | 2 | 0 | ['C', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | Python3 concise solution with stack beats 95% | python3-concise-solution-with-stack-beat-ab3o | \tclass Solution:\n\t\tdef smallestSubsequence(self, text: str) -> str: \n\t\t\tdict={}\n\t\t\tfor i in range(len(text)):\n\t\t\t\tdict[text[i]]=i\n\t\t\ | jasperjoe | NORMAL | 2019-06-16T00:22:54.683230+00:00 | 2019-06-16T00:22:54.683272+00:00 | 510 | false | \tclass Solution:\n\t\tdef smallestSubsequence(self, text: str) -> str: \n\t\t\tdict={}\n\t\t\tfor i in range(len(text)):\n\t\t\t\tdict[text[i]]=i\n\t\t\tstack=[]\n\t\t\tfor i in range(len(text)):\n\t\t\t\tif text[i] in stack:\n\t\t\t\t\tcontinue\n\t\t\t\twhile stack and stack[-1]>text[i] and dict[stack[-1]]>i:\n\t\t\t\t\t\tstack.pop()\n\t\t\t\tif text[i] not in stack:\n\t\t\t\t\tstack.append(text[i])\n\t\t\treturn \'\'.join(stack) | 2 | 0 | ['Stack', 'Python3'] | 1 |
smallest-subsequence-of-distinct-characters | Java greedy solution | java-greedy-solution-by-demonmikalis-6hrh | We use greedy method here, first iterate all the characters in text, if we find the current one is smaller than already added ones, the push the current in the | demonmikalis | NORMAL | 2019-06-14T00:04:09.564295+00:00 | 2019-06-14T00:04:09.564362+00:00 | 405 | false | We use greedy method here, first iterate all the characters in text, if we find the current one is smaller than already added ones, the push the current in the front and pop back the already added\n```\n public String smallestSubsequence(String text) {\n\t\t int[] count = new int[26];\n\t\t for(int i=0;i<text.length();i++) {\n\t\t\t char c = text.charAt(i);\n\t\t\t count[c-\'a\']++;\n\t\t }\n\t\t \n\t\t boolean[] used = new boolean[26];\n\t\t Arrays.fill(used,false);\n\t\t StringBuilder sb = new StringBuilder();\n\t\t for(int i=0;i<text.length();i++) {\n\t\t\t char c = text.charAt(i);\n\t\t\t if(used[c-\'a\']) {\n\t\t\t\t count[c-\'a\']--;\n\t\t\t\t continue;\n\t\t\t }\n\t\t\t int last = sb.length()-1;\n\t\t\t while(sb.length()>0 && c<sb.charAt(last) && count[sb.charAt(last)-\'a\']>0) {\n\t\t\t\t used[sb.charAt(last)-\'a\'] = false;\n\t\t\t\t sb.deleteCharAt(last);\n\t\t\t\t last-=1;\n\t\t\t }\n\t\t\t used[c-\'a\'] = true;\n\t\t\t sb.append(c);\n\t\t\t count[c-\'a\']--;\n\t\t }\n\t\t \n\t\t \n\t\t return sb.toString();\n\t\t\n\t }\n\t\n``` | 2 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | O(N^2) solution with bitmasks | on2-solution-with-bitmasks-by-todor91-20jo | For each position save set with all characters after that position and\nsave set with needed characters. And in each iteration find the minimal\ncharacter that | todor91 | NORMAL | 2019-06-13T10:16:41.118651+00:00 | 2019-06-13T10:18:14.562655+00:00 | 259 | false | For each position save set with all characters after that position and\nsave set with needed characters. And in each iteration find the minimal\ncharacter that has set with all needed characters and erase the needed character.\n```\n bool isSubset(int big, int small) {\n for (int i = 0; i < 30; ++i) {\n if ((small & (1 << i)) && !((big & (1 << i)))) {\n return false;\n }\n }\n return true;\n }\n \n string smallestSubsequence(string text) {\n int all = 0;\n string T;\n map<int, int> M;\n\n T = text;\n for (char c : text) all |= (1 << (c - \'a\'));\n \n for (int i = 0 ; i < T.size(); ++i) {\n M[i] = 0;\n for (int j = i; j < T.size(); ++j) {\n M[i] |= (1 << (T[j] - \'a\'));\n }\n }\n \n string res;\n int i = 0;\n while (all) {\n while (!(all & (1 << (T[i] - \'a\')))) i++;\n int best = i;\n for (int j = i; j < T.size(); ++j) {\n if (!(all & (1 << (T[j] - \'a\')))) continue;\n if (T[j] < T[best] && isSubset(M[j],all)) {\n best = j;\n }\n }\n res.push_back(T[best]);\n all &= ~(1 << (T[best] - \'a\'));\n i = best;\n }\n return res;\n }\n``` | 2 | 0 | [] | 1 |
smallest-subsequence-of-distinct-characters | Java Solution - Greedy (1ms, 100%) | java-solution-greedy-1ms-100-by-extreman-6wka | First we find out the list of distinct chars with acs order.\nFor each char, if all other chars can be found after the char, then accept the char and remove it | extremania | NORMAL | 2019-06-11T07:28:53.257344+00:00 | 2019-06-11T07:34:12.748997+00:00 | 242 | false | First we find out the list of distinct chars with acs order.\nFor each char, if all other chars can be found after the char, then accept the char and remove it from the list, else try next char.\n\n```\nclass Solution {\n\tString check(String str, char c, List<Character> clist) {\n\t\tint idx = str.indexOf(c);\n\t\tString s0 = str.substring(idx + 1);\n\n\t\tfor (char c0 : clist)\n\t\t\tif (c0 == c)\n\t\t\t\tcontinue;\n\t\t\telse if (s0.indexOf(c0) < 0)\n\t\t\t\treturn null;\n\t\treturn s0;\n\t}\n\n\tpublic String smallestSubsequence(String text) {\n\n\t\tString text0 = text;\n\n\t\tint[] arr = new int[26];\n\t\tfor (char c : text0.toCharArray())\n\t\t\tarr[c - \'a\']++;\n\n\t\tList<Character> clist = new ArrayList<>();\n\t\tfor (int i = 0; i < arr.length; i++)\n\t\t\tif (arr[i] > 0)\n\t\t\t\tclist.add((char) (\'a\' + i));\n\n\t\tStringBuilder result = new StringBuilder();\n\t\twhile (clist.size() > 0) {\n\t\t\tIterator<Character> it = clist.iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tchar next = it.next();\n\t\t\t\tString checked = check(text0, next, clist);\n\t\t\t\tif (checked != null) {\n\t\t\t\t\ttext0 = checked;\n\t\t\t\t\tit.remove();\n\t\t\t\t\tresult.append(next);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result.toString();\n\t}\n}\n``` | 2 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | Java solution using stack with explanation | java-solution-using-stack-with-explanati-6kv7 | Use a stack to maintain a running sequence of smallest subsequence. \n2. Iterate over the test string and check in the queue 1. if the character is visites befo | siddhantiitbmittal3 | NORMAL | 2019-06-09T21:53:44.239311+00:00 | 2019-06-10T02:22:30.403596+00:00 | 312 | false | 1. Use a stack to maintain a running sequence of smallest subsequence. \n2. Iterate over the test string and check in the queue 1. if the character is visites before 2. if the character is smaller than the head of the queue 3. if the head of the queue is has more occurence later.\n3. if all the above condition we remove the head and we continue doing this untill queue is empty or head dont satisfy this condtion.\n\n\n```\nclass Solution {\n public String smallestSubsequence(String text) {\n Deque<Character> s = new LinkedList<Character>();\n\n\n int[] count = new int[26];\n\n for(int i=0;i<text.length();i++){\n count[text.charAt(i)-97]++;\n }\n\n boolean[] visited = new boolean[26];\n\n for(int i=0;i<text.length();i++){\n\n char c = text.charAt(i);\n\n if(!visited[c-97]){\n while(!s.isEmpty() && s.peek() > c && count[s.peek()-97] > 0){\n visited[s.peek()-97] = false;\n s.pop();\n }\n\n s.push(c);\n visited[c-97] = true;\n }\n count[text.charAt(i)-97]--;\n }\n\n String out = "";\n\n while(!s.isEmpty()){\n out = s.pop() + out;\n }\n\n return out;\n }\n}\n``` | 2 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | Simple Java Solution✅💻 | simple-java-solution-by-rubiksolve-aoje | Code | RubikSolve | NORMAL | 2025-04-03T16:01:39.352487+00:00 | 2025-04-03T16:01:39.352487+00:00 | 32 | false |
# Code
```java []
import java.util.*;
class Solution {
public String smallestSubsequence(String s) {
Map<Character, Integer> freq = new HashMap<>();
Set<Character> set = new HashSet<>();
Stack<Character> stack = new Stack<>();
for (char ch : s.toCharArray()) {
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
}
for (char ch : s.toCharArray()) {
freq.put(ch, freq.get(ch)-1);
if (set.contains(ch)) continue;
while (!stack.isEmpty() && stack.peek() > ch && freq.get(stack.peek()) > 0) {
set.remove(stack.pop());
}
stack.push(ch);
set.add(ch);
}
StringBuilder res = new StringBuilder();
for (char ch : stack) {
res.append(ch);
}
return res.toString();
}
}
``` | 1 | 0 | ['String', 'Stack', 'Greedy', 'Monotonic Stack', 'Java'] | 0 |
smallest-subsequence-of-distinct-characters | ✅ 100% Accepted | Easy Approach | JAVA & C++ 💎 | 100-accepted-easy-approach-java-c-by-ora-wx3s | IntuitionIntuition that i got is that...
That if i pick a character then what is the probability that the character will reappear in the future and it will give | Orangjustice777 | NORMAL | 2025-01-21T12:54:20.516790+00:00 | 2025-01-21T12:54:20.516790+00:00 | 192 | false | 
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Intuition that i got is that...
That if i pick a character then what is the probability that the character will reappear in the future and it will give smallest lexico string
# Approach
So , the problem is that how do i store the appearence of character in the future
```
int[] freq = new int[26];
int n = s.length();
for(int i = 0 ; i < n ; i++){
char c = s.charAt(i);
freq[c - 'a'] = i ;
}
```
this was sorted by this method of keeping the last index of the occurence of the character
Now the next problem was that how to pick the smallest letter first such that all the characters appear after it that is if the string contains 'a' theres no guarentee that all the rest alphabets will appear in the future
so this was solved by
Adding each letter in the string
then checking if a character smaller than the last character has appeared
if yes and it satisfies the condition that it appears again in the future then we can remove the last character and append the new character in the string
and this is kept in the while loop as series of letters will be removed if a smaller letter appears
For eg .
```
while(sb.length() > 0 && sb.charAt(sb.length()-1) - c > 0 && (freq[sb.charAt(sb.length()-1) - 'a'] > i)){
char toBeDeleted = sb.charAt(sb.length()-1);
visited[toBeDeleted-'a'] = false ;
sb.deleteCharAt(sb.length()-1);
}
```
"bcdabcd" --> "bcd" is the result
when 'a' appears and we check that the letter 'd' appears again in the future with the help of freq array
then pop 'd'
similarly we check this condtion with 'c' and 'b'
this loop leads to the removal of "bcd" and 'a' gets the first places
thus we got the smallest lexicographical string
Do this a dry run then you'll get it
If helpful please upvote
thank you
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
$$O(n)$$
- Space complexity:
$$O(n)$$
# Code
```java []
class Solution {
public String removeDuplicateLetters(String s) {
int[] freq = new int[26];
int n = s.length();
for(int i = 0 ; i < n ; i++){
char c = s.charAt(i);
freq[c - 'a'] = i ;
}
boolean[] visited = new boolean[26];
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < n ; i++){
char c = s.charAt(i);
int idx = c - 'a';
if(visited[idx] == false){
while(sb.length() > 0 && sb.charAt(sb.length()-1) - c > 0 && (freq[sb.charAt(sb.length()-1) - 'a'] > i)){
char toBeDeleted = sb.charAt(sb.length()-1);
visited[toBeDeleted-'a'] = false ;
sb.deleteCharAt(sb.length()-1);
}
sb.append(c);
visited[idx] = true ;
}
}
return sb.toString();
}
}
```
```C++ []
class Solution {
public:
string removeDuplicateLetters(string s) {
int freq[26] = {0}; // Frequency array to track last index of each character
int n = s.length();
// Fill frequency array with the last index of each character
for (int i = 0; i < n; i++) {
freq[s[i] - 'a'] = i;
}
bool visited[26] = {false}; // Visited array to track if a character is already in the result
string result;
for (int i = 0; i < n; i++) {
char c = s[i];
int idx = c - 'a';
// Skip if the character is already in the result
if (visited[idx]) continue;
// Remove characters from the result if:
// - The result is not empty
// - The last character in the result is greater than the current character
// - The last character exists later in the string
while (!result.empty() && result.back() > c && freq[result.back() - 'a'] > i) {
char toBeDeleted = result.back();
visited[toBeDeleted - 'a'] = false; // Mark as not visited
result.pop_back(); // Remove the last character
}
// Add the current character to the result and mark it as visited
result.push_back(c);
visited[idx] = true;
}
return result;
}
};
```
```java []
class Solution {
public String smallestSubsequence(String s) {
//Monotonic Stack Usage
Stack<Character> st = new Stack<>();
int n = s.length();
//lastIndex
int[] lastIndex = new int[26];
for(int i = 0 ; i < n ; i++){
int idx = s.charAt(i) - 'a';
lastIndex[idx] = i ;
}
//Visited array so that we only add the character once
boolean[] visited = new boolean[26];
//Now we create the stack
for(int i = 0 ; i < n ; i++){
char c = s.charAt(i);
int idx = c - 'a';
if(visited[idx] == false){
while(!st.isEmpty() && (st.peek() - c) > 0 && lastIndex[st.peek() - 'a'] > i){
visited[st.peek()-'a'] = false ;
st.pop();
}
st.push(c);
visited[idx] = true ;
}
}
//Now we take out the string from stack
StringBuilder sb = new StringBuilder();
while(!st.isEmpty()){
sb.append(st.peek());
st.pop();
}
return sb.reverse().toString();
}
}
```
| 1 | 0 | ['Java'] | 0 |
smallest-subsequence-of-distinct-characters | same question as leetcode 316 | same-question-as-leetcode-316-by-gayatri-vzy5 | # Intuition \n\n\n\n\n\n# Complexity\n- Time complexity: O(N)\n\n\n- Space complexity: O(1)\n\n\n# Code\ncpp []\nclass Solution {\npublic:\n string smalles | Gayatrik_22 | NORMAL | 2024-10-09T06:23:03.586429+00:00 | 2024-10-09T06:23:03.586464+00:00 | 32 | false | <!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n vector<int> freq(26, 0); // Frequency array to count occurrences\n vector<bool> inStack(26, false); // Tracks characters in the stack\n stack<char> st; // Stack to build the result\n\n // Step 1: Count the frequency of each character in the string\n for (char c : s) {\n freq[c - \'a\']++;\n }\n\n // Step 2: Iterate through the string\n for (char c : s) {\n freq[c - \'a\']--; // Decrease the frequency count for the current character\n\n // If the character is already in the stack, skip it\n if (inStack[c - \'a\']) continue;\n\n // Step 3: Maintain the stack in lexicographical order\n // While the stack is not empty and the top character is greater than the current character\n // and the top character will appear again later, pop the stack\n while (!st.empty() && st.top() > c && freq[st.top() - \'a\'] > 0) {\n inStack[st.top() - \'a\'] = false; // Mark the top character as not in the stack\n st.pop(); // Pop the top character\n }\n\n // Step 4: Push the current character onto the stack\n st.push(c);\n inStack[c - \'a\'] = true; // Mark the current character as in the stack\n }\n\n // Step 5: Build the result from the stack\n string result = "";\n while (!st.empty()) {\n result += st.top(); // Add the top character to the result\n st.pop(); // Pop the top character\n }\n\n // Reverse the result string to get the correct order\n reverse(result.begin(), result.end());\n return result; // Return the final result\n \n }\n};\n``` | 1 | 0 | ['String', 'Stack', 'Greedy', 'Monotonic Stack', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | beats 100% user with cpp | beats-100-user-with-cpp-by-sakshi_chaudh-uduc | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | sakshi_chaudhary1703 | NORMAL | 2024-09-20T16:46:59.841802+00:00 | 2024-09-20T16:46:59.841836+00:00 | 256 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n int n = s.size();\n string ans = "";\n vector<bool> taken(27 , false);\n vector<int> lastOcc(27 , 0);\n for(int i = 0 ; i< n ; i++){\n lastOcc[s[i] - \'a\'] = i ; \n }\n for(int i = 0 ; i< n ; i++){\n if(taken[s[i] - \'a\']) continue;\n if(ans.size()== 0 || ans.back() <s[i]){\n ans+= s[i];\n taken[s[i] - \'a\'] = true;\n }\n else{\n while(ans.size()>0 && ans.back()>s[i] && lastOcc[ans.back()-\'a\'] > i){\n \n taken[ans.back()-\'a\'] = false;\n ans.pop_back() ;\n }\n ans+= s[i];\n taken[s[i] - \'a\'] = true;\n }\n }\n return ans;\n // map<char,int> mp;\n // for(auto t: s){\n // mp[t]++;\n // }\n // string ans = "";\n // int fr =0 ;\n // for(int i = 0 ; i< n; i++){\n // if(mp[s[i]] == 0) continue;\n // if(mp[s[i]] ==1){\n // mp[s[i]]--;\n // cout<<s[i]<<endl;\n // ans += s[i];\n // }else{\n // int j = i+1 ; \n // map<char,int> dp = mp;\n // int cnt = i ; \n // char c = s[i];\n // dp[s[j]]--;\n // while(dp[s[j]] !=1 && j<n){\n // cout<<j<<" "<<dp[s[j]]<<" "<<s[j]<<endl;\n // if(s[j]<c && dp[s[j]] >1 )\n // {\n // cnt = j ; \n // c = s[j];\n // }\n // dp[s[j]]--;\n // j++;\n // }\n // if(j<n){\n // if(c>s[j]){\n // cout<<s[j]<<" "<<j<<endl;\n // cnt = j ; \n // c = s[j];\n // }\n // }\n // while(i<cnt ){\n // mp[s[i]]--;\n // i++;\n // }\n // ans+=c;\n // mp[c] = 0 ;\n // cout<<i<<" "<<c<<endl;\n // cout<<fr<<endl;\n // fr++;\n // }\n // }\n // return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
smallest-subsequence-of-distinct-characters | beats 100% user with cpp with TC explaination | beats-100-user-with-cpp-with-tc-explaina-fznb | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | gyuyul | NORMAL | 2024-08-31T05:55:32.129491+00:00 | 2024-08-31T05:55:32.129524+00:00 | 99 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\na bit of confusion that may arise is that there are nested for loop \nso time complexity should be quadratic.If this question arises in your mind then you are on right path. So, let\'s clear the confusion , \nhere the ans can be of length 26 at most ... so the while loop which is poping the element from ans can run for at most 26 time .. \nso time complexity will be 26*n but in big O notaion we don\'t consider constant that\'s why at most places you will find the TC \nfor this will be O(n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n int n = s.size();\n string ans = "";\n vector<bool> taken(27 , false);\n vector<int> lastOcc(27 , 0);\n for(int i = 0 ; i< n ; i++){\n lastOcc[s[i] - \'a\'] = i ; \n }\n for(int i = 0 ; i< n ; i++){\n if(taken[s[i] - \'a\']) continue;\n if(ans.size()== 0 || ans.back() <s[i]){\n ans+= s[i];\n taken[s[i] - \'a\'] = true;\n }\n else{\n while(ans.size()>0 && ans.back()>s[i] && lastOcc[ans.back()-\'a\'] > i){\n \n taken[ans.back()-\'a\'] = false;\n ans.pop_back() ;\n }\n ans+= s[i];\n taken[s[i] - \'a\'] = true;\n }\n }\n return ans;\n // map<char,int> mp;\n // for(auto t: s){\n // mp[t]++;\n // }\n // string ans = "";\n // int fr =0 ;\n // for(int i = 0 ; i< n; i++){\n // if(mp[s[i]] == 0) continue;\n // if(mp[s[i]] ==1){\n // mp[s[i]]--;\n // cout<<s[i]<<endl;\n // ans += s[i];\n // }else{\n // int j = i+1 ; \n // map<char,int> dp = mp;\n // int cnt = i ; \n // char c = s[i];\n // dp[s[j]]--;\n // while(dp[s[j]] !=1 && j<n){\n // cout<<j<<" "<<dp[s[j]]<<" "<<s[j]<<endl;\n // if(s[j]<c && dp[s[j]] >1 )\n // {\n // cnt = j ; \n // c = s[j];\n // }\n // dp[s[j]]--;\n // j++;\n // }\n // if(j<n){\n // if(c>s[j]){\n // cout<<s[j]<<" "<<j<<endl;\n // cnt = j ; \n // c = s[j];\n // }\n // }\n // while(i<cnt ){\n // mp[s[i]]--;\n // i++;\n // }\n // ans+=c;\n // mp[c] = 0 ;\n // cout<<i<<" "<<c<<endl;\n // cout<<fr<<endl;\n // fr++;\n // }\n // }\n // return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
smallest-subsequence-of-distinct-characters | Searching wether the element we are removing can be removed or not? | searching-wether-the-element-we-are-remo-gvth | Writing the solution so that it stays in my find and for future reference.\n# Intuition\n Describe your first thoughts on how to solve this problem. \nMontonic | ronitroushan21102 | NORMAL | 2023-09-26T18:45:35.835991+00:00 | 2023-09-26T18:45:35.836012+00:00 | 89 | false | Writing the solution so that it stays in my find and for future reference.\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMontonic stack idea comes into the mind when the core idea behind a monotonic stack is to maintain a stack of elements in such a way that the elements in the stack either strictly increase or strictly decrease (depending on the problem requirements).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere the question demands that we have to make the ans lexicographically sorted with no duplicates.\n\nSo we have to remove the larger number which have occured before.\nWe can only delete the larger element if its index occur after the current element.\n\n# Code\n```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n stack<char>st;\n map<char,vector<int>>mp; \n vector<int>vis(26,0);\n for(int i =0 ; i< s.size() ;i++)\n {\n mp[s[i]].push_back(i);\n }\n for(int i = 0 ; i < s.size() ;i++)\n {\n while(!st.empty()&&s[i] < st.top()&&vis[s[i]-\'a\']==0)\n {\n vector<int>indices = mp[st.top()];\n auto ind = upper_bound(indices.begin(),indices.end(),i);\n\n if(ind !=indices.end())\n {\n vis[st.top()-\'a\']=0;\n st.pop();\n }\n else\n {\n break;\n }\n }\n if(vis[s[i]-\'a\']==0){\n vis[s[i]-\'a\'] =1;\n st.push(s[i]);\n }\n }\n string ans="";\n while(!st.empty())\n {\n ans+=st.top();\n st.pop();\n }\n reverse(ans.begin(),ans.end());\n \n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
smallest-subsequence-of-distinct-characters | Beats 100% C++ | Monotonic Stack | beats-100-c-monotonic-stack-by-aglakshya-myof | Approach\nWe have to choose the biggest element at as last as possible,\nfor that we keep a track of when every element is occuring last in the array.\nNow we h | aglakshya02 | NORMAL | 2023-09-26T16:00:31.759669+00:00 | 2023-09-26T16:08:56.168174+00:00 | 4 | false | # Approach\nWe have to choose the biggest element at as last as possible,\nfor that we keep a track of when every element is occuring last in the array.\nNow we have to keep the order as monotonic as possible so we decide to use a monotonic stack.\nWhile pushing any element we check that - \n* it should not be already pushed\n* We pop all the bigger elements that that element provided we can find those elements somtime later in the array during our iteration.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(26)\n\n# Code\n```\nclass Solution {\npublic:\n string smallestSubsequence(string a) {\n int n=a.size();\n unordered_map<char,int>last;\n unordered_map<char,int>pushed;\n for(int i=0;i<n;i++) last[a[i]]=i;\n\n stack<char>s;\n\n for(int i=0;i<n;i++){\n if(s.empty()){\n s.push(a[i]);\n pushed[a[i]]=true;\n continue;\n }\n\n while(!s.empty() && s.top()>=a[i] && last[s.top()]>=i && pushed[a[i]]==false){\n pushed[s.top()]=false;\n s.pop();\n }\n\n if(pushed[a[i]]==false){\n s.push(a[i]);\n pushed[a[i]]=true;\n }\n }\n\n string ans;\n\n while(!s.empty()){\n ans.push_back(s.top());\n s.pop();\n }\n\n reverse(ans.begin(),ans.end());\n\n return ans;\n }\n};\n``` | 1 | 0 | ['Monotonic Stack', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | 🔥Beats 100% | EASY | Clean Code | Stack | C++ | | beats-100-easy-clean-code-stack-c-by-ant-hyh0 | Code\n\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n stack<char> st;\n unordered_map<char, int> last_occ;\n unor | Antim_Sankalp | NORMAL | 2023-09-26T09:48:20.565160+00:00 | 2023-09-26T09:48:20.565181+00:00 | 6 | false | # Code\n```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n stack<char> st;\n unordered_map<char, int> last_occ;\n unordered_set<char> visit;\n\n for (int i = 0; i < s.size(); i++)\n {\n last_occ[s[i]] = i;\n }\n\n for (int i = 0; i < s.size(); i++)\n {\n char c = s[i];\n if (!visit.count(c))\n {\n while (!st.empty() && c < st.top() && i < last_occ[st.top()])\n {\n visit.erase(st.top());\n st.pop();\n }\n st.push(c);\n visit.insert(c);\n }\n }\n\n string res = "";\n while (!st.empty())\n {\n res = st.top() + res;\n st.pop();\n }\n\n return res;\n }\n};\n``` | 1 | 0 | ['String', 'Stack', 'Monotonic Stack', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | C++ Easy 0ms faster || stack | c-easy-0ms-faster-stack-by-mdadnan28713-74au | \n\n# Code\n\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n vector<int> last(26,-1);\n int n=s.length();\n for(in | mdadnan28713 | NORMAL | 2023-08-24T14:46:12.692721+00:00 | 2024-02-23T17:09:49.550019+00:00 | 14 | false | \n\n# Code\n```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n vector<int> last(26,-1);\n int n=s.length();\n for(int i=0;i<n;i++){\n last[s[i]-\'a\']=i;\n }\n vector<bool> visited(26,false);\n stack<char> st;\n for(int i=0;i<n;i++){\n if(visited[s[i]-\'a\'])\n continue;\n while(!st.empty() && s[i]<st.top() && last[st.top()-\'a\']>i){ \n visited[st.top()-\'a\']=false;\n st.pop();\n } \n st.push(s[i]);\n visited[s[i]-\'a\']=true; \n }\n string ans="";\n while(!st.empty()){\n ans=st.top()+ans;\n st.pop();\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Stack', 'Greedy', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | Easy Python Solution | easy-python-solution-by-rajatganguly-3sg6 | ```\nclass Solution:\n def smallestSubsequence(self, s: str) -> str:\n d={v:k for k,v in enumerate(s)}\n stack=[]\n for k,v in enumerate | RajatGanguly | NORMAL | 2022-11-08T10:10:12.798069+00:00 | 2022-11-08T10:10:12.798114+00:00 | 89 | false | ```\nclass Solution:\n def smallestSubsequence(self, s: str) -> str:\n d={v:k for k,v in enumerate(s)}\n stack=[]\n for k,v in enumerate(s):\n if v not in stack:\n while stack and stack[-1]>v and d[stack[-1]]>k:\n stack.pop()\n stack.append(v)\n return "".join(stack) | 1 | 0 | ['Stack', 'Python', 'Python3'] | 0 |
smallest-subsequence-of-distinct-characters | Python Easy Monotonic Stack | python-easy-monotonic-stack-by-anu1rag-52ix | Intuition\ncheckout https://leetcode.com/problems/remove-duplicate-letters/solutions/2666355/python-easy-stack-o-n/\n Describe your first thoughts on how to sol | anu1rag | NORMAL | 2022-10-05T22:09:58.599780+00:00 | 2022-10-05T22:09:58.599819+00:00 | 53 | false | # Intuition\ncheckout https://leetcode.com/problems/remove-duplicate-letters/solutions/2666355/python-easy-stack-o-n/\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def smallestSubsequence(self, s: str) -> str:\n count = Counter(s)\n stack = deque()\n result = set()\n for i in s:\n if i in result: \n count[i] -= 1\n continue\n\n while(stack and stack[-1] > i and count[stack[-1]] > 1):\n count[stack[-1]] -= 1\n result.remove(stack[-1])\n stack.pop()\n\n stack.append(i)\n result.add(i)\n\n return "".join(stack)\n``` | 1 | 0 | ['Stack', 'Monotonic Stack', 'Python3'] | 0 |
smallest-subsequence-of-distinct-characters | C++ Approach Using Stack , Unorderd_map and Set | c-approach-using-stack-unorderd_map-and-pfbj8 | The Below solution uses stack , unordered_map and set into its implementation\n\nstring smallestSubsequence(string s)\n {\n stack<char>st;\n se | geekyleetcoder | NORMAL | 2022-10-03T18:57:51.172425+00:00 | 2022-10-03T18:57:51.172462+00:00 | 161 | false | The Below solution uses stack , unordered_map and set into its implementation\n```\nstring smallestSubsequence(string s)\n {\n stack<char>st;\n set<char>se;\n unordered_map<char,int>mp;\n string res = "";\n int n = s.length();\n for(int i=0;i<n;i++)\n {\n mp[s[i]] = i;\n }\n for(int i=0;i<n;i++)\n {\n if(se.find(s[i])!=se.end())\n {\n continue;\n }\n while(st.empty()!=true && st.top()>=s[i] && mp[st.top()]>i)\n {\n int val = st.top();\n st.pop();\n se.erase(val);\n }\n st.push(s[i]);\n se.insert(s[i]);\n }\n while(st.empty()!=true)\n {\n res.push_back(st.top());\n st.pop();\n }\n reverse(res.begin(),res.end());\n return res;\n }\n```\n**If you find solution helpful and easy to understand please UPVOTE**\n**Happy Coding** | 1 | 0 | ['Stack', 'Ordered Set', 'C++'] | 0 |
smallest-subsequence-of-distinct-characters | Simplest Fastest Quickest JAVA Solution via Stack all himself by Lord Noddy | simplest-fastest-quickest-java-solution-a2ls4 | \nclass Solution {\n public String smallestSubsequence(String s) {\n int [] lastIndex=new int[26];\n for(int i=0;i<s.length();i++)\n | 2001640100013 | NORMAL | 2022-09-28T06:53:55.838097+00:00 | 2022-09-28T06:53:55.838145+00:00 | 1,016 | false | ```\nclass Solution {\n public String smallestSubsequence(String s) {\n int [] lastIndex=new int[26];\n for(int i=0;i<s.length();i++)\n lastIndex[s.charAt(i)-\'a\'] = i;\n boolean [] seen=new boolean[26];\n Stack<Integer> st=new Stack<>();\n \n for(int i=0;i<s.length();i++)\n {\n int c=s.charAt(i) - \'a\';\n \n if(seen[c]) continue;\n \n while(!st.isEmpty() && st.peek()>c && i < lastIndex[st.peek()])\n {\n seen[st.pop()] = false;\n }\n st.push(c);\n seen[c]=true;\n }\n StringBuilder sb=new StringBuilder();\n \n while(!st.isEmpty())\n {\n sb.append((char) (st.pop() + \'a\'));\n }\n return sb.reverse().toString();\n \n }\n}\n``` | 1 | 0 | ['Monotonic Stack', 'Java'] | 1 |
smallest-subsequence-of-distinct-characters | Easy Python solution with stack & set | easy-python-solution-with-stack-set-by-s-bqjb | \tclass Solution:\n\t\tdef smallestSubsequence(self, s: str) -> str:\n\t\t\tnew = {}\n\t\t\tfor i in range(len(s)):\n\t\t\t\tnew[s[i]]=i\n\t\t\tstak,seen=[],set | SaiManoj1234 | NORMAL | 2022-09-10T11:37:12.137308+00:00 | 2022-09-10T11:37:12.137336+00:00 | 496 | false | \tclass Solution:\n\t\tdef smallestSubsequence(self, s: str) -> str:\n\t\t\tnew = {}\n\t\t\tfor i in range(len(s)):\n\t\t\t\tnew[s[i]]=i\n\t\t\tstak,seen=[],set()\n\t\t\tfor i in range(len(s)):\n\t\t\t\tif s[i] not in seen:\n\t\t\t\t\twhile stak and new[stak[-1]]>i and stak[-1]>s[i]:\n\t\t\t\t\t\tseen.remove(stak[-1])\n\t\t\t\t\t\tstak.pop()\n\t\t\t\t\tstak.append(s[i])\n\t\t\t\t\tseen.add(s[i])\n\t\t\treturn "".join(stak)\n | 1 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | Smallest Subsequence of Distinct Characters (easiest explanation) | smallest-subsequence-of-distinct-charact-rzis | \nstring smallestSubsequence(string s) {\n// we will take the stack which will store the elements so that we can delete the \n// useless element | amandeep0210 | NORMAL | 2022-08-26T17:56:06.716859+00:00 | 2022-08-26T17:56:06.716916+00:00 | 116 | false | ```\nstring smallestSubsequence(string s) {\n// we will take the stack which will store the elements so that we can delete the \n// useless elements.\n stack<char> st;\n// now we will make a map which will store the frequency of each element\n unordered_map<char, int> freq;\n for(auto it : s){\n freq[it]++;\n }\n// Now we will make a map which will tell use wheter we used the current element or not\n unordered_map<char, bool>check;\n for(int i = 0 ; i< s.length(); i++){\n check[s[i]] = false; \n }\n// there will be different cases now ;\n for(int i = 0 ; i< s.size(); i++){\n// we will decrease the freq each time when we face partivular element \n freq[s[i]]--;\n// if the element is used then we will skip that \n if(check[s[i]])continue;\n else{\n \n \n// if st.top() is greater than the current element then we will remove the previous \n// elemtent if the frequency of that elemtent is greater than zero i.e the top \n// elemtent is present somewhere after the current element .\n while( st.size() and st.top() > s[i] and freq[st.top()]){\n// the elements which i removed i will make there check as false as those are\n// present somewhere after the current element i.e they will be checked in \n// future\n check[st.top()]= false;\n st.pop();\n \n }\n// we will add each element into the stack\n st.push(s[i]);\n check[s[i]]= true;\n }\n \n }\n// now store the result into a string \n string res = "";\n \n while(!st.empty())\n {\n res.push_back(st.top());\n \n st.pop();\n }\n// as stack is storing the elements so reverse the result\n reverse(res.begin(), res.end());\n \n return res;\n }\n``` | 1 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | [C++] || MonoStack | c-monostack-by-rahul921-lemd | \nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n string ans = "" ;\n int f[26] = {} , taken[26] = {} ;\n for(auto | rahul921 | NORMAL | 2022-08-24T16:48:08.453041+00:00 | 2022-08-24T16:48:08.453083+00:00 | 221 | false | ```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n string ans = "" ;\n int f[26] = {} , taken[26] = {} ;\n for(auto &x : s) ++f[x-\'a\'] ;\n \n for(auto &x : s){\n --f[x-\'a\'] ;\n while(ans.size() and x < ans.back() and f[ans.back() - \'a\'] and !taken[x-\'a\']) taken[ans.back()-\'a\'] = 0 , ans.pop_back() ;\n if(!taken[x-\'a\']) ans.push_back(x) , taken[x-\'a\'] = 1 ; \n }\n \n return ans ;\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
smallest-subsequence-of-distinct-characters | beats 100% , idea is to think as per the frequency whether it can add to result or not | beats-100-idea-is-to-think-as-per-the-fr-whgm | \nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n vector<int> a(26,0);\n \n int u = 0;\n for(auto i: s)\n | mr_stark | NORMAL | 2022-08-05T13:05:51.465385+00:00 | 2022-08-05T13:05:51.465418+00:00 | 34 | false | ```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n vector<int> a(26,0);\n \n int u = 0;\n for(auto i: s)\n {\n a[i-\'a\']++;\n if(a[i-\'a\']==1)\n u++;\n }\n \n string ans = "";\n map<char,bool> mp;\n\n for(int i=0;i<s.length();i++)\n {\n \n while(mp[s[i]]==false && ans.length()>0 && ans.back()>s[i] && a[ans.back()-\'a\']>=1)\n {\n mp[ans.back()]=false; \n ans.erase(ans.begin()+ans.size()-1);\n }\n \n if(mp[s[i]]==false){\n ans.push_back(s[i]);\n mp[s[i]]=true;\n }\n a[s[i]-\'a\']--;\n }\n \n \n return ans;\n \n }\n};\n``` | 1 | 0 | [] | 0 |
smallest-subsequence-of-distinct-characters | C++ solution using stack | c-solution-using-stack-by-ephemeral_live-pjqf | Dry Run\nINPUT - "cbacdcbc"\n\n\ni = 0\nans = \'c\'\nExplaination - Since c not considered\n\n\n\ni = 1\nans = \'b\'\nExplaination - Since c is present afterwar | ephemeral_lives | NORMAL | 2022-07-11T08:26:47.541182+00:00 | 2022-07-11T08:26:47.541220+00:00 | 106 | false | Dry Run\nINPUT - "cbacdcbc"\n\n```\ni = 0\nans = \'c\'\nExplaination - Since c not considered\n```\n\n```\ni = 1\nans = \'b\'\nExplaination - Since c is present afterwards, we can remove the c added before\n```\n\n```\ni = 2\nans = \'a\'\nExplaination - Since b is present afterwards, we can remove the b added before\n```\n\n```\ni = 3\nans = \'ac\'\nExplaination - Since c not considered till now. Note previously considered c has been remove. Same has to be reflected in the bool array.\n```\n\n```\ni = 4\nans = \'acd\'\nExplaination - Since d not considered till now\n```\n\n```\ni = 5\nans = \'acd\'\nExplaination - c already considered\n```\n\n```\ni = 6\nans = \'acdb\'\nExplaination - Eventhough d is greater than b, it is not removed as d doesn\'t appear afterwards. Add b at the end.\n```\n\n```\ni = 7\nans = \'acdb\'\nExplaination - c already considered.\n```\n\nFINAL ANSWER - \'acdb\'\n\nCODE - \n\n```\nclass Solution {\npublic:\n string smallestSubsequence(string s) {\n \n // store array of last index in s\n vector<int> lastIdx (26, 0);\n for(int i = 0 ; i < s.size() ; i++)\n lastIdx[int(s[i])- int(\'a\')] = i;\n \n // bool array to store if the char has been considered\n vector<bool> isAdded (26, false);\n \n stack<char> k;\n for(int i = 0; i < s.size() ; i++){\n // if char already present then continue\n if (isAdded[int(s[i]) - int(\'a\')])\n continue;\n \n // if char to be added is smaller than top of \n // stack and the char at top of stack is present\n // later, then pop.\n // continue till possible\n while(!k.empty() && k.top() > s[i] && i < lastIdx[int(k.top()) - int(\'a\')]){\n isAdded[int(k.top()) - int(\'a\')] = false;\n k.pop();\n }\n \n // add to stack and mark as added\n isAdded[int(s[i])-int(\'a\')] = true;\n k.push(s[i]);\n \n }\n \n // traverse through stack and create ans\n string ans = "";\n while(!k.empty()){\n ans = k.top() + ans;\n k.pop();\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Stack', 'C'] | 1 |
product-sales-analysis-iii | SIMPLE | USING CTE & MIN() & Group By & Inner Join | simple-using-cte-min-group-by-inner-join-0owd | Complexity\nTime complexity: O(N)^2\nwhere N is the number of rows satisfying the conditions.\n\n# Space complexity: \nO(1)^2\n\n# Code\n\n# Write your MySQL qu | bamshankar130295 | NORMAL | 2024-04-16T07:33:04.064142+00:00 | 2024-04-16T07:33:04.064172+00:00 | 15,218 | false | # Complexity\nTime complexity: O(N)^2\nwhere N is the number of rows satisfying the conditions.\n\n# Space complexity: \nO(1)^2\n\n# Code\n```\n# Write your MySQL query statement below\n\nWITH CTE AS (\n SELECT product_id, MIN(year) AS minyear FROM Sales \n GROUP BY product_id \n)\n\nSELECT s.product_id, s.year AS first_year, s.quantity, s.price \nFROM Sales s\nINNER JOIN CTE ON cte.product_id = s.product_id AND s.year = cte.minyear; \n```\n\n | 74 | 0 | ['MySQL', 'MS SQL Server', 'PostgreSQL'] | 5 |
product-sales-analysis-iii | ✅EASY MYSQL SOLUTION | easy-mysql-solution-by-swayam28-pcgn | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | swayam28 | NORMAL | 2024-08-16T08:00:34.739236+00:00 | 2024-08-16T08:00:34.739263+00:00 | 14,590 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n\n```\n# Write your MySQL query statement below\nselect product_id,year as first_year, quantity, price\nfrom Sales\nwhere(product_id, year) in (select product_id, min(year) from Sales group by product_id)\n``` | 68 | 0 | ['MySQL'] | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.