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
maximum-binary-string-after-change
Python (Simple Maths)
python-simple-maths-by-rnotappl-n72d
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
rnotappl
NORMAL
2024-03-21T15:47:43.313453+00:00
2024-03-21T15:47:43.313484+00:00
11
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```\nclass Solution:\n def maximumBinaryString(self, binary):\n n, count = len(binary), 0\n\n ans = ["1"]*n\n\n for i in range(n):\n if binary[i] == "0":\n count += 1 \n\n for i in range(n):\n if binary[i] == "0":\n ans[i+count-1] = "0"\n return "".join(ans)\n\n return binary\n```
0
0
['Python3']
0
maximum-binary-string-after-change
easy python solution, beats 100% 🔥🔥
easy-python-solution-beats-100-by-aditya-3qm8
Intuition\n Describe your first thoughts on how to solve this problem. \nProperty:\nA binary number is maximum when its \'1\'s occupy more significant positions
adityauday2002
NORMAL
2024-02-28T13:43:38.637686+00:00
2024-02-28T13:43:38.637725+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nProperty:\nA binary number is maximum when its \'1\'s occupy more significant positions (left)\n\nInference from rules :\n "00" can be changed to "10"\n "10" can be changed to "01" -> allows us to move any number of zeroes towards complete left\n\nso moving all the zeroes to left and converting "00" to "10" will give the maximum number possible\n\nNote:\nleave the 1\'s present in leftmost positions unaltered, as they are already in ideal position\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nstarting from left of binary string, count the leading number of ones , say \'i\', and initialize the result string with \'i\' number of ones\n\ncount the number of zeroes in the string, say \'c\', from the rule - "00" can be converted to "10", c-1 zeroes can be converted to ones, so append (c-1) \'1\' + \'0\' to resultant string\n\nappend the remaining number of ones to resultant string to obtain the final result\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1), (constant)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def maximumBinaryString(self, binary):\n i,l = 0,len(binary)\n while i<l and binary[i]==\'1\':i+=1\n c = binary.count(\'0\')\n return \'1\'*i+\'1\'*(c-1)+\'0\'*(1 if c>0 else 0)+\'1\'*(l-i-c)\n\n\n\n \n \n \n \n```
0
0
['Python']
0
maximum-binary-string-after-change
JS || Solution by Bharadwaj
js-solution-by-bharadwaj-by-manu-bharadw-isp4
Code\n\nvar maximumBinaryString = function (binary) {\n let zeroCount = 0, firstZeroIndex = -1;\n for (let i = 0; i < binary.length; i++) {\n let c
Manu-Bharadwaj-BN
NORMAL
2024-02-27T05:47:25.631634+00:00
2024-02-27T05:47:25.631673+00:00
52
false
# Code\n```\nvar maximumBinaryString = function (binary) {\n let zeroCount = 0, firstZeroIndex = -1;\n for (let i = 0; i < binary.length; i++) {\n let char = binary[i];\n if (char === \'0\') {\n zeroCount++;\n if (firstZeroIndex === -1) firstZeroIndex = i;\n }\n }\n let resultArray = new Array(binary.length).fill(1);\n resultArray[firstZeroIndex + zeroCount - 1] = 0;\n return resultArray.join(\'\');\n};\n```
0
0
['JavaScript']
1
maximum-binary-string-after-change
Greedy Intuitive Solution. JAVA O(n)
greedy-intuitive-solution-java-on-by-cha-dsjq
Intuition\n Describe your first thoughts on how to solve this problem. We need to push the leftmost 0 as far to the right as possible. We can always move this 0
Charlemagne5t
NORMAL
2024-02-22T15:42:27.077018+00:00
2024-02-22T15:42:27.077046+00:00
29
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->We need to push the leftmost 0 as far to the right as possible. We can always move this 0 to the 1 index to the right, repeating the given operations from the next zero to the left. By doing so, we can observe the pattern: we use one zero to push the leftmost zero to the right, and the total number of zeroes decreases by 1. Therefore, we just need to find the position of the leftmost zero and count all the other zeroes. The final string would consist of all ones, except for the one zero that we pushed as far as we had other zeroes. So, if the index of the leftmost zero is i, and we have k zeroes to spare, the resulting position of the 0 would be [i + k].\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGreedy\n\n# Complexity\n- Time complexity:\n- O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String maximumBinaryString(String binary) {\n int n = binary.length();\n char[] chars = binary.toCharArray();\n int firstZero = -1;\n int shift = 0;\n for(int i = 0; i < n; i++){\n if(chars[i] == \'0\'){\n if(firstZero == -1){\n firstZero = i;\n }else shift++;\n }\n \n }\n if(firstZero == -1){\n return binary;\n }\n char[] ans = new char[n];\n Arrays.fill(ans, \'1\');\n ans[firstZero + shift] = \'0\';\n return new String(ans);\n }\n}\n```
0
0
['Java']
0
maximum-binary-string-after-change
C++ Solution
c-solution-by-lotus18-7wtw
Code\n\nclass Solution \n{\npublic:\n string maximumBinaryString(string binary)\n {\n int stOnes=0, n=binary.size(), i=0, z=0;\n while(i<n &
lotus18
NORMAL
2024-01-03T07:11:45.310740+00:00
2024-01-03T07:11:45.310770+00:00
10
false
# Code\n```\nclass Solution \n{\npublic:\n string maximumBinaryString(string binary)\n {\n int stOnes=0, n=binary.size(), i=0, z=0;\n while(i<n && binary[i++]==\'1\') stOnes++;\n for(int x=0; x<n; x++) \n {\n if(binary[x]==\'0\') z++;\n binary[x]=\'1\';\n }\n if(stOnes<n) binary[stOnes+z-1]=\'0\';\n return binary;\n }\n};\n```
0
0
['C++']
0
maximum-binary-string-after-change
Final Recursive Form | Commented and Explained
final-recursive-form-commented-and-expla-9rgd
Intuition\n Describe your first thoughts on how to solve this problem. \nIn the intuition, I\'m stepping through the start of the problem and the outline of the
laichbr
NORMAL
2023-11-18T15:44:36.629027+00:00
2023-11-18T15:44:36.629044+00:00
22
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn the intuition, I\'m stepping through the start of the problem and the outline of the example as a recursive backtrack. Backtracking is not used here, but serves to inform the thinking process and outline some things worth finding in pursuing the solution. \n\nFirst, note that with operations, we can make the final string at most contain 1 zero (could have a string of all 1\'s, in which case we can do nothing, or have a single zero then all 1\'s, same situation). \n\nThis leads to the second realization, which is that if we do not have at least 2 zeroes, we are in fact already maximized (either it\'s one zero and all ones, or a 1 followed by some number of 1s, a zero, and then some number of 1s, in which case any switch is in fact worse) \n\nLooking at the first example (in comments), note that we can in fact group all of the zeroes on the left -> 0000111 (did not show in walk through, but it is in fact possible) \n\nThis means we can isolate the zeros before the switch process takes place \nHow many should we do then? \n\nBased on our answer above to switching zeros, one less than the total number of zeroes! This means we will \n\n- Find unconverted portion as the binary string up to the first zero (leave leading 1\'s alone) \n- Find the number of converted zeroes (one less than total number of zeroes) \n- Find the number of remaining zeroes -> there\'s only 1 \n- Find the number of non-leading-ones -> length of string less first zero (how much unconverted actually is) less the number of zeroes (how many already accounted for) \n- Build string as unconverted portion + number of converted zeroes + a single 0 + number of non leading ones -> this is your answer \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGet length of string \nGet number of zeros \nif less than two zeroes -> return binary \notherwise, build as outlined in intuition and return converted string \n\n# Complexity\n- Time complexity : O(n) \n - O(n) to get number of zeros and first zero index \xA0\n\n- Space complexity : O(n) stores final binary string \n\n# Code\n```\nclass Solution:\n def maximumBinaryString(self, binary: str) -> str:\n # binary string is binary \n # if number contains 00 -> can replace with 10 \n # if number contains 10 -> can replace with 01 \n # return maximum binary string you can obtain after any number of operations \n # 000110 \n # 100110 # do any 00 first \n # 110110 # no 00, but 10 at back. Try doing 10 at back and search for improvement. \n # 110101 # no 00 but 10 at back. Try doing 10 at back and search for improvement. \n # 110011 # do any 00 first. \n # 111011 # no 00, but 10 at back. Try doing 10 at back and search for improvement. \n # 110111 # no 00, but 10 at back. Try doing 10 at back and search for improvement. \n # 101111 # no 00, but 10 at back. Try doing 10 at back and search for improvement. \n # 011111 # no 00, no 10, stop, recurse backwards. Report best found along the way. \n # hint 1 -> note with operations, can make the string only contain at most 1 zero \n # hint 2 -> less than 2 zeros in input string, return it \n # python -> string.count(char, start, end) \n bL = len(binary)\n num_zeroes = binary.count(\'0\', 0, bL)\n if num_zeroes < 2 : \n return binary \n else : \n # hint 3 -> through operations all 0\'s can be grouped while pushing 1\'s down \n # -> means you can always convert all but 1 zero into a 1 \n # hint 4 -> how far to the left should we push the zeros? leftmost 0 should never be \n # -> pushed further to the left as that would just knock out 1\'s already higher up \n # hint 5 -> considering length of string can be large, time efficient way to construct output? \n # -> \n # taken together, can group all 0\'s, then get length of zeros \n # with length of zeros take one less. At this index less one should be a zero \n # All others should be ones \n # get the leftmost index of zero as we read left to right \n zero_index = binary.index(\'0\') \n # unconverted portion then is based on this index \n unconverted_portion = binary[:zero_index]\n # we can convert num_zeroes less 1 to 1\'s \n converted_zeroes = \'1\' * (num_zeroes - 1) \n # we will have at most 1 remaining zeroes \n remaining_zeroes = \'0\' \n # we will have some non leading ones -> length of string less first index of zero less number of zeros -> cannot be negative \n number_of_non_leading_ones = bL - zero_index - num_zeroes\n if number_of_non_leading_ones < 0 : \n number_of_non_leading_ones = 0 \n unconverted_ones = \'1\' * number_of_non_leading_ones \n # build converted string in order of operations final form \n converted_string = unconverted_portion + converted_zeroes + remaining_zeroes + unconverted_ones \n # return converted string \n return converted_string\n\n```
0
0
['Python3']
0
maximum-binary-string-after-change
Easy to understand JavaScript solution (Greedy)
easy-to-understand-javascript-solution-g-yh64
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n\nvar maximumBinaryString = function(binary) {\n const size = binary.length;\n
tzuyi0817
NORMAL
2023-10-08T08:24:04.728921+00:00
2023-10-08T08:24:04.728946+00:00
1
false
# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nvar maximumBinaryString = function(binary) {\n const size = binary.length;\n const splitBinary = binary.split(\'\');\n let zero = start = 0;\n\n for (let index = 0; index < size; index++) {\n const str = binary[index];\n\n if (str === \'0\') zero += 1;\n else if (zero === 0) start += 1;\n splitBinary[index] = \'1\';\n }\n if (size !== start) splitBinary[start + zero - 1] = \'0\';\n\n return splitBinary.join(\'\');\n};\n```
0
0
['JavaScript']
0
maximum-binary-string-after-change
[C++] cakewalk
c-cakewalk-by-bidibaaz123-ettn
Intuition\nI took some sample test cases and tried to find some pattern, I got a thought that:\n- Try to move all 0\'s using 10->01 transformation and then appl
bidibaaz123
NORMAL
2023-10-02T12:37:00.280067+00:00
2023-10-02T12:39:42.579331+00:00
24
false
# Intuition\nI took some sample test cases and tried to find some pattern, I got a thought that:\n- Try to move all **0\'s** using **10->01** transformation and then apply \n**00->10** transformation , if there are **n** zeros where **n>=2** , maximum of **n-1** 1\'s can be there in resultant string\n\n# Approach\nI took some sample test cases and tried to find some pattern, I got a thought that:\n- If there is a single **\'0\'** or all **\'1\'s** the best solution is to leave string as it as , as in case of single **\'0\'** if we try to move it leftwards it will remove higher set bits.\n- Also if there are terminal **0\'s** leftwards collecting all of them at the starting will help in setting higher bits.\n- If there are none of terminal **0\'s** leftwards, try to find first **\'0\'** and shift all other zeros besides it\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$ \n\n# Code\n```\nclass Solution {\npublic:\n void createResultString(int count0, int count1, string &result){\n for(int i=1 ;i<=count0-1;i++)\n result+="1";\n\n result+="0";\n\n for(int i=1; i<=count1; i++)\n result+="1";\n }\n string maximumBinaryString(string binary) {\n int count0 = 0;\n int count1 = 0;\n string result = "";\n for(int i=0; i<binary.size(); i++){\n if(binary[i] == \'0\')\n count0++;\n else\n count1++;\n }\n \n\n if(count0 == 0 || count0 == 1)\n return binary;\n \n int it = 0;\n while(true){\n if(binary[it] == \'1\'){\n result+="1";\n count1--;\n }\n else\n break;\n it++;\n }\n createResultString(count0, count1, result);\n return result;\n }\n};\n```
0
0
['C++']
0
maximum-binary-string-after-change
Explain use c#
explain-use-c-by-thanhtung3001-gyhf
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
ThanhTung3001
NORMAL
2023-09-24T09:01:47.797175+00:00
2023-09-24T09:01:47.797195+00:00
2
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```\npublic class Solution {\n public string MaximumBinaryString(string binary) {\n int zeros = 0;\n int firstZero = -1;\n for (int i = 0; i < binary.Length; i++){\n if (binary[i] == \'0\'){\n zeros++;\n if (firstZero == -1) firstZero = i;\n }\n }\n if (zeros < 2) return binary;\n StringBuilder sb = new();\n sb.Append(\'1\', firstZero + (zeros - 1));\n sb.Append("0");\n sb.Append(\'1\', binary.Length - sb.Length);\n return sb.ToString();\n }\n}\n```
0
0
['C#']
0
maximum-binary-string-after-change
Maximum Binary String After Change
maximum-binary-string-after-change-by-sa-frlv
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
Sam_Neamah
NORMAL
2023-09-21T03:54:59.577587+00:00
2023-09-21T03:54:59.577642+00:00
1
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 * @param {string} binary\n * @return {string}\n */\nfunction maximumBinaryString(s) {\n let ones = 0;\n let zeros = 0;\n const n = s.length;\n let res = \'1\'.repeat(n);\n\n for (let i = 0; i < n; ++i) {\n if (s.charAt(i) === \'0\') {\n zeros++;\n } else if (zeros === 0) {\n ones++;\n }\n }\n\n if (ones < n) {\n res = res.substring(0, ones + zeros - 1) + \'0\' + res.substring(ones + zeros);\n }\n\n return res;\n}\n\n\n\n```
0
0
['JavaScript']
0
maximum-binary-string-after-change
C# One pass O(n) solution. Very effecient.
c-one-pass-on-solution-very-effecient-by-sgf5
Intuition\n Describe your first thoughts on how to solve this problem. \nGiven the operations available in the problem statement, we can always group together z
Cocamo1337
NORMAL
2023-09-07T01:46:44.920284+00:00
2023-09-07T01:46:44.920312+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGiven the operations available in the problem statement, we can always group together zeros by "pushing" ones further down. The question at this stage becomes "When and where do we group the zeros".\n\nIf we can always group the zeros, then we can also always convert every zero except 1 into ones.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFind the full count of zeros, as well as the index of the leftMost zero.\n\nIf the count of zeros in the input string is less than or equal to 1, then we can just return the input string, because moving a zero up wouldn\'t allow for any conversion and it would just be pushing ones further down in the process.\n\nIf the count of zeros is greater than 1, that\'s where the fun begins! Well, not really, since the rest is very simple. Basically if the count is greater than 1 we can start constructing our new string using a StringBuilder object. First, use the append method to append \'1\' to our sb, with the second arguement being the number of times it appends. In this case we want to append \'1\' (first zero index + (number of zeros minus 1)) times. This might seem random, but if we reason it out:\n\nLets say first zero index is 2. If we append \'1\' 2 times then spots 0 and 1 will be filled with \'1\'. Meaning next index is index 2 - the space where the first zero is.\n\nThen we add (count of zeros - one) \'1\'s, which functions as converting every zero except one into a \'1\'.\n\nNext, we append our single \'0\'.\n\nand finally we fill the rest of the space difference between the input string length and our string builders length with \'1\'s, since we know we "used" all zeros in our previous operations.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) - we go over the entire length of the input string one time while collecting our "zeros" data.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) we use a SB object which will store an equivelent number of characters to the input string.\n\n# Code\n```\npublic class Solution {\n public string MaximumBinaryString(string binary) {\n int zeros = 0;\n int firstZero = -1;\n for (int i = 0; i < binary.Length; i++){\n if (binary[i] == \'0\'){\n zeros++;\n if (firstZero == -1) firstZero = i;\n }\n }\n if (zeros < 2) return binary;\n StringBuilder sb = new();\n sb.Append(\'1\', firstZero + (zeros - 1));\n sb.Append("0");\n sb.Append(\'1\', binary.Length - sb.Length);\n return sb.ToString();\n }\n}\n```
0
0
['C#']
0
maximum-binary-string-after-change
beautiful greedy
beautiful-greedy-by-zedzogrind-umw0
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
zedzogrind
NORMAL
2023-08-31T21:58:33.617696+00:00
2023-08-31T21:58:33.617723+00:00
29
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```\nclass Solution:\n def maximumBinaryString(self, binary: str) -> str:\n zero_count = binary.count("0") - 1\n leftmost_zero = binary.find("0")\n if leftmost_zero == -1:\n return binary\n adjust = min(len(binary) - 1, leftmost_zero + zero_count)\n\n return "1" * adjust + "0" + "1" * ((len(binary) - 1) - adjust)\n\n```
0
0
['Python3']
0
maximum-binary-string-after-change
Nothing But Greedy Only
nothing-but-greedy-only-by-tus_tus-wfx2
Intuition\nWe will try to convert maximum number of zero into one.\n\nObservations -> using the operations we can convert \n\n111110 -> 011111\n100000 -> 00
Tus_Tus
NORMAL
2023-08-11T10:41:22.434663+00:00
2023-08-11T10:41:22.434693+00:00
10
false
# Intuition\n**We will try to convert maximum number of zero into one.\n\nObservations -> using the operations we can convert \n\n111110 -> 011111\n100000 -> 000001\n000000 -> 111110\n\n\nSo, basically the position of zero is not of great importance here, we can bring all the zero at one place. And then perform the necessary operations**\n\n\n\n```\nclass Solution {\npublic:\n string maximumBinaryString(string binary) {\n\n\n int n = binary.size();\n int zero = 0;\n\n for(int i = 0; i < n; i++) {\n if(binary[i] == \'0\') zero++;\n }\n\n string ans = "";\n\n for(int i = 0; i < n; i++) {\n ans += \'1\';\n }\n\n for(int i = 0; i < n; i++) {\n if(binary[i] == \'0\') {\n int poss = i + zero - 1;\n ans[poss] = \'0\';\n break;\n }\n }\n\n\n return ans;\n }\n};\n```
0
0
['C++']
0
maximum-binary-string-after-change
Explained || Greedy || simple shifting || pattern intuitive
explained-greedy-simple-shifting-pattern-i5j5
\nclass Solution {\npublic:\n string maximumBinaryString(string b) {\n int n=b.size();\n int zc=0;\n string ans(n,\'1\');\n for(int i=0;i<n;i
chaudharyarya76
NORMAL
2023-08-02T05:19:58.042198+00:00
2023-08-02T05:19:58.042220+00:00
5
false
```\nclass Solution {\npublic:\n string maximumBinaryString(string b) {\n int n=b.size();\n int zc=0;\n string ans(n,\'1\');\n for(int i=0;i<n;i++){\n if(b[i]==\'0\')\n zc++;\n }\n for(int i=0;i<n;i++){\n if(b[i]==\'0\'){\n ans[i+zc-1]=\'0\';\n return ans;\n }\n }\n return ans;\n }\n};\n\n// 000110\n// 10->01\n// 00->10\n//point to note are final answer will contain only 1 zero \n//2. shift the leftmost zero to the index which is equal to count of number of zero why this to maximize are answer jitna last mai hoga utna maximize answer hoga :)\n \n\n\n```\nPlease upvote if you like the solution
0
0
['C']
0
maximum-binary-string-after-change
Super Simple Solution!!!⚡🔥🔥
super-simple-solution-by-yashpadiyar4-7hrl
\n\n# Code\n\nclass Solution {\npublic:\n string maximumBinaryString(string binary) {\n int n=binary.size();\n long long zero=0;\n for(i
yashpadiyar4
NORMAL
2023-07-09T19:01:35.061144+00:00
2023-07-09T19:01:35.061162+00:00
30
false
\n\n# Code\n```\nclass Solution {\npublic:\n string maximumBinaryString(string binary) {\n int n=binary.size();\n long long zero=0;\n for(int i=0;i<binary.size();i++){\n if(binary[i]==\'0\')zero++;\n }\n int idx=-1;\n for(int i=0;i<binary.size();i++){\n if(binary[i]==\'0\'){\n idx=i;\n break;\n }\n } \n string ans(n,\'1\');\n if(zero>0)ans[idx+zero-1]=\'0\';\n return ans;\n }\n};\n```
0
0
['String', 'Greedy', 'C++']
0
maximum-binary-string-after-change
Easy||Greedy||C++
easygreedyc-by-rohit_18kumar-w8az
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
rohit_18kumar
NORMAL
2023-06-26T07:25:03.058660+00:00
2023-06-26T07:25:03.058683+00:00
16
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```\nclass Solution {\npublic:\n string maximumBinaryString(string s) {\n int n=s.length();\n if(n==1){\n return s;\n }\n int count=0;\n int i;\n for(auto it:s){\n if(it==\'0\'){\n count++;\n }\n }\n string ans="";\n for(i=0;i<n;i++){\n if(s[i]==\'0\'){\n break;\n }\n else{\n ans+=s[i];\n }\n }\n if(i==n){\n return ans;\n }\n while(count>1){\n ans+=\'1\';\n count--;\n i++;\n\n }\n ans+=\'0\';\n int x=ans.length();\n x=n-x;\n while(x>0){\n ans+=\'1\';\n x--;\n }\n return ans;\n\n\n \n }\n};\n```
0
0
['C++']
0
maximum-binary-string-after-change
C++ Greedy
c-greedy-by-abhishek6487209-zba0
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
Abhishek6487209
NORMAL
2023-06-20T06:45:49.902400+00:00
2023-06-20T06:45:49.902427+00:00
16
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```\nclass Solution {\npublic:\n string maximumBinaryString(string binary) {\n int n = binary.size();\n int cnt=0,k=-1; \n for(int i = 0; i < n; i++)\n {\n if(binary[i]==\'0\'){\n if(k==-1)\n k= i;\n else\n cnt++;\n }\n }\n for(int i = 0; i < n; i++)\n {\n if((k+cnt)== i)\n binary[i] = \'0\';\n else\n binary[i] = \'1\';\n }\n return binary;\n }\n};\n```
0
0
['C++']
0
maximum-binary-string-after-change
🔥Simplest Java code, single pass, O(n), faster than 100%, with explanation🔥
simplest-java-code-single-pass-on-faster-0htx
Intuition\nAt the end, the string will contain atmost one 0.\nWe want to find that one index at which this 0 will exist(if it should).\nCall that index lastIdx\
iworkouthere
NORMAL
2023-06-11T19:35:24.830997+00:00
2023-06-11T19:35:24.831043+00:00
70
false
# Intuition\nAt the end, the string will contain atmost one 0.\nWe want to find that one index at which this 0 will exist(if it should).\nCall that index lastIdx\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nFirst of all we don\'t at all care about 1s.\nWe will always look for a pair of zeroes.\nWhen we reach the second zero of a pair, we manipulate the pair of zeroes, it results in only a single 0, whose index is 1 greater than the first 0 in the pair. \nBoth first and second 0s in the pair become 1.\nThus, similarly, we go on hunting for the next pair(actually second 0 of next pair, because first 0 is the one we just created!), and keep manipulating.\nThe index of the resultant 0 from each manipulation will be lastIdx.\nUltimetly, whatever value we finally have in lastIdx is the index where that one 0 in the ans string will exist.\n\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```\nclass Solution {\n public String maximumBinaryString(String binary) {\n int lastIdx = -1;\n char[] num = binary.toCharArray();\n\n for(int i = 0; i < num.length; i++) {\n if(num[i] == \'0\') {\n if(lastIdx == -1) lastIdx = i;\n else lastIdx++;\n }\n }\n\n StringBuilder ans = new StringBuilder();\n ans.append("1".repeat(num.length));\n if(lastIdx == -1) return ans.toString(); \n ans.replace(lastIdx, lastIdx + 1, "0");\n return ans.toString();\n }\n}\n```\n\n# PLEASE UPVOTE IF YOU FOUND IT HELPFUL! (AND SMART ;) )\n\n
0
0
['Java']
0
maximum-binary-string-after-change
Easy CPP solution | Greedy
easy-cpp-solution-greedy-by-rahulpatwal-roma
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
rahulpatwal
NORMAL
2023-06-10T16:50:23.675294+00:00
2023-06-10T16:50:23.675321+00:00
24
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```\nclass Solution {\npublic:\n string maximumBinaryString(string binary) {\n int cnt = 0;\n int n = binary.size();\n for(int i=0; i<n; i++){\n cnt += binary[i]==\'0\' ? 1 : 0;\n }\n if(cnt<=1){\n return binary;\n }\n int index = -1;\n for(int i=0; i<n; i++){\n if(binary[i]==\'0\' && index==-1){\n index = i;\n }\n binary[i] = \'1\';\n }\n // if(index==-1){\n // return binary;\n // }\n binary[index+cnt-1] = \'0\';\n return binary;\n }\n};\n```
0
0
['Greedy', 'C++']
0
maximum-binary-string-after-change
Maximum Binary String After Change
maximum-binary-string-after-change-by-wa-znqd
--------------- Easy C++ Solution -----------------------\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\npu
wajid94571
NORMAL
2023-05-05T13:11:46.649925+00:00
2023-05-05T13:11:46.649981+00:00
19
false
--------------- Easy C++ Solution -----------------------\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n string maximumBinaryString(string binary) {\n int zeros = 0;\n int n=binary.size();\n string ans(n,\'1\');\n for (auto& c : binary) {\n if (c == \'0\') {\n ++zeros;\n }\n }\n for (int i=0;i<n;i++) {\n if (binary[i] == \'0\') {\n ans[i+zeros-1]=\'0\';\n return ans;\n }\n }\n \n return ans;\n }\n};\n```
0
0
['C++']
0
maximum-binary-string-after-change
JS (JavaScript) fast simple solution. O(n)
js-javascript-fast-simple-solution-on-by-88s8
\n# Code\n\n/**\n * @param {string} binary\n * @return {string}\n */\nvar maximumBinaryString = function(binary) {\n let firstZero = 0\n let zeroCounter =
YarDrago
NORMAL
2023-03-28T15:06:44.063366+00:00
2023-03-28T15:06:44.063412+00:00
21
false
\n# Code\n```\n/**\n * @param {string} binary\n * @return {string}\n */\nvar maximumBinaryString = function(binary) {\n let firstZero = 0\n let zeroCounter = 0\n for (let i = binary.length - 1; i >= 0; i--){\n if (binary[i] === "0"){\n zeroCounter++\n firstZero = i\n }\n }\n if (zeroCounter === 0) return binary\n let firstPath = firstZero + zeroCounter - 1\n if (firstPath <= 0) return "0" + "1".repeat(binary.length - 1)\n else return "1".repeat(firstPath) + "0" + "1".repeat(binary.length - 1 - firstPath)\n};\n```
0
0
['JavaScript']
0
maximum-binary-string-after-change
C and C++
c-and-c-by-tinachien-bapr
C solution\n\nchar * maximumBinaryString(char * binary){\n int n = strlen(binary) ;\n int firstZeroIdx = -1 ;\n for(int i = 0; i < n; i++){\n if
TinaChien
NORMAL
2023-03-24T00:22:16.131764+00:00
2023-03-24T00:24:05.656541+00:00
10
false
C solution\n```\nchar * maximumBinaryString(char * binary){\n int n = strlen(binary) ;\n int firstZeroIdx = -1 ;\n for(int i = 0; i < n; i++){\n if(binary[i] == \'1\')\n continue ;\n if(firstZeroIdx >= 0){\n binary[firstZeroIdx] = \'1\' ;\n binary[firstZeroIdx+1] = \'0\' ;\n firstZeroIdx++ ;\n binary[i] = \'1\' ;\n }\n else{\n if(i < n-1 && binary[i+1] == \'0\')\n binary[i] = \'1\' ;\n else\n firstZeroIdx = i ;\n }\n }\n return binary ;\n}\n```\nC++ solution\n```\nclass Solution {\npublic:\n string maximumBinaryString(string binary) {\n int n = binary.size() ;\n int firstZeroIdx = -1 ;\n for(int i = 0; i < n; i++){\n if(binary[i] == \'1\')\n continue ;\n if(firstZeroIdx >= 0){\n binary[firstZeroIdx] = \'1\' ;\n binary[firstZeroIdx+1] = \'0\' ;\n firstZeroIdx++ ;\n binary[i] = \'1\' ;\n }\n else{\n if(i < n-1 && binary[i+1] == \'0\')\n binary[i] = \'1\' ;\n else\n firstZeroIdx = i ;\n }\n }\n return binary ;\n }\n};\n```
0
0
[]
0
maximum-binary-string-after-change
Easy Faster Efficient Java Soln
easy-faster-efficient-java-soln-by-devan-j04a
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
devanshsrivastava707
NORMAL
2023-03-23T22:35:39.688278+00:00
2023-03-23T22:35:39.688307+00:00
59
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```\nclass Solution {\n public String maximumBinaryString(String binary) {\n int n = binary.length();\n int zeros = 0, ones = 0;\n for(int i = 0; i < n; i++){\n char ch = binary.charAt(i);\n if(ch == \'0\'){\n zeros++;\n } else if(zeros == 0){\n ones++;\n }\n }\n StringBuilder sb = new StringBuilder("1".repeat(n));\n if(ones < n){\n sb.setCharAt(ones + zeros - 1, \'0\');\n }\n return sb.toString(); \n }\n}\n```
0
0
['String', 'Java']
0
maximum-binary-string-after-change
CPP | EASY
cpp-easy-by-mahipalpatel11111-17by
class Solution {\npublic:\n string maximumBinaryString(string b) \n {\n int l=-1;\n for(int i=0;i<b.length();++i)\n {\n if(b[
mahipalpatel11111
NORMAL
2023-03-06T07:13:42.141433+00:00
2023-03-06T07:13:42.141475+00:00
8
false
class Solution {\npublic:\n string maximumBinaryString(string b) \n {\n int l=-1;\n for(int i=0;i<b.length();++i)\n {\n if(b[i]==\'0\')\n {\n if(l==-1)\n l=i;\n else\n {\n b[i]=\'1\';\n b[l]=\'1\';\n ++l;\n b[l]=\'0\';\n }\n }\n }\n return b;\n }\n};
0
0
[]
0
maximum-binary-string-after-change
C++ greedy approach
c-greedy-approach-by-user5976fh-k9e2
\nclass Solution {\npublic:\n string maximumBinaryString(string binary) {\n // goal: add all already most left 1\'s to ans\n // push any 1\'s p
user5976fh
NORMAL
2023-02-23T05:48:16.597326+00:00
2023-02-23T05:48:16.597373+00:00
17
false
```\nclass Solution {\npublic:\n string maximumBinaryString(string binary) {\n // goal: add all already most left 1\'s to ans\n // push any 1\'s past that to the most right\n // if there is only 1 zero it should stay the same\n // fill out all the empty 0 space with 1s except the most right 0 space\n int i = 0;\n string ans = "";\n while (i < binary.size() && binary[i] == \'1\')\n ans += binary[i++];\n // count the number of 1s and 0s left\n int oneC = 0, zeroC = 0;\n while (i < binary.size()){\n oneC += binary[i] == \'1\';\n zeroC += binary[i++] == \'0\';\n }\n for (i = 0; i < zeroC - 1; ++i) ans += \'1\';\n if (zeroC > 0) ans += \'0\';\n for (i = 0; i < oneC; ++i) ans += \'1\';\n return ans; \n }\n};\n```
0
0
[]
0
maximum-binary-string-after-change
Simple Explained Solution
simple-explained-solution-by-darian-cata-7p3g
\n\nclass Solution {\n public String maximumBinaryString(String s) {\n int ones = 0, zeros = 0, n = s.length();\n StringBuilder res = new Strin
darian-catalin-cucer
NORMAL
2023-02-11T07:34:49.711083+00:00
2023-02-11T07:34:49.711122+00:00
77
false
\n```\nclass Solution {\n public String maximumBinaryString(String s) {\n int ones = 0, zeros = 0, n = s.length();\n StringBuilder res = new StringBuilder("1".repeat(n));\n for (int i = 0; i < n; ++i) {\n if (s.charAt(i) == \'0\')\n zeros++;\n else if (zeros == 0)\n ones++;\n }\n if (ones < n)\n res.setCharAt(ones + zeros - 1, \'0\');\n return res.toString();\n }\n}\n```
0
0
['Swift', 'Java', 'Go', 'Ruby', 'Bash']
0
maximum-binary-string-after-change
50 ms Python solution
50-ms-python-solution-by-czjnbb-x5fo
We will have only one 0 in the final string, and its position is determined by the position of first 0 and number of 0s.\n\n# Code\n\nclass Solution(object):\n
czjnbb
NORMAL
2023-02-07T00:01:20.404058+00:00
2023-02-07T00:04:50.844206+00:00
39
false
We will have only one 0 in the final string, and its position is determined by the position of first 0 and number of 0s.\n\n# Code\n```\nclass Solution(object):\n def maximumBinaryString(self, binary):\n """\n :type binary: str\n :rtype: str\n """\n\n n0 = binary.count(\'0\')\n if n0 < 2: return binary\n ll = len(binary)\n p0 = binary.index(\'0\')\n return \'1\' * (p0 + n0 - 1) + \'0\' + \'1\' * (ll - p0 - n0)\n```
0
0
['Python']
0
maximum-binary-string-after-change
Preserve leading ones and maximize on remaining
preserve-leading-ones-and-maximize-on-re-7zj4
\nclass Solution:\n def maximumBinaryString(self, binary: str) -> str:\n n = len(binary)\n i = 0\n while i < n and binary[i] == "1":\n
theabbie
NORMAL
2023-02-04T03:20:48.320661+00:00
2023-02-04T03:20:48.320703+00:00
22
false
```\nclass Solution:\n def maximumBinaryString(self, binary: str) -> str:\n n = len(binary)\n i = 0\n while i < n and binary[i] == "1":\n i += 1\n o = z = 0\n for j in range(i, n):\n if binary[j] == "0":\n z += 1\n else:\n o += 1\n return "1" * i + "1" * max(z - 1, 0) + "0" * min(z, 1) + "1" * o\n```
0
0
[]
0
maximum-binary-string-after-change
Magic solution
magic-solution-by-tttc-g7qw
I don\'t remember how I figured out this pattern\n\n# Code\n\nclass Solution:\n def maximumBinaryString(self, binary: str) -> str:\n idx = binary.find
tttc
NORMAL
2023-01-31T04:21:20.524976+00:00
2023-01-31T04:21:20.525006+00:00
98
false
I don\'t remember how I figured out this pattern\n\n# Code\n```\nclass Solution:\n def maximumBinaryString(self, binary: str) -> str:\n idx = binary.find(\'01\')\n if idx == -1:\n return \'1\' * (len(binary) - 1) + binary[-1]\n n = idx + binary[idx:].count(\'0\')\n return \'1\' * (n - 1) + \'0\' + \'1\' * (len(binary) - n)\n```
0
0
['Python3']
0
lexicographically-minimum-string-after-removing-stars
O(n) - min heap with indices vector || with DRY RUN
on-min-heap-with-indices-vector-with-dry-m0d1
Intuition \nOnce we reduce the string, all the indices of the string will get messed up! So DON\'T reduce the original string initially.\nInstead, replace the e
SubBuffer
NORMAL
2024-06-02T04:02:44.013811+00:00
2024-08-09T17:43:13.760488+00:00
5,869
false
## Intuition \nOnce we reduce the string, all the indices of the string **will get messed up**! So **DON\'T reduce** the original string initially.\n*Instead*, replace the elements with something other than English letters. I replaced them with __!__. \n\n## Needed Data Structures\nI) save the characters in a _heap_, i.e. ```priority_queue<char>``` in C++, ```PriorityQueue<Character>``` in Java, ```PriorityQueue()``` in Python.\n\nII) save the character indices in a _vector_ of _vector_, i.e. ```vector<vector<int>>``` in C++, ```ArrayList<ArrayList<Integer>>``` in Java, or ```[[]]``` in Python.\n\n## Approach\nDefine a **priority queue (min heap)** to memorize what is *the smallest character*; save the indices of the characters in a different vector. This is to remove the highest index of the smallest character first. Otherwise, lexiographically, we will have a bigger string. Thus, build the priority_queue **comparison** rule and check the indices vector to make sure it is not empty. If index is empty, then pop from the heap as well.\n\n## Complexity:\n```\nTime: O(n*log(26)) = O(n) // O(log(26)) maintaining heap; O(n) to iterate the string\nSpace: O(26) + O(2*n) = O(n) // O(26) heap; O(n) for indices vector and O(n) for result\n```\n## Code\n<iframe src="https://leetcode.com/playground/F7mknzZA/shared" frameBorder="0" width="500" height="700"></iframe>\n\n## Dry run `(skip if you understand the code)`\nThe dryrun below is valid for above __C++__ code. But for __Java__ and __Python__, I use a _HashSet_ instead of in-place string change, so for those two, the below dryrun is only good to an extent. For C++, it is accurate. If you have any problems, ask in the comments.\n\nSuppose `s = "a a b * d * z d *"` , then the iterations according to the code is like the following: \n```\nheap state initially: `{}`\nindices vector state initially: `{{}, {} , {}, ....., {} , {}}`\n```\n**Iteration 1:**\n```\n \uD83D\uDC47\ns = "a a b * d * z d *"\n```\n```\nheap: `{a\uD83D\uDC48}` \nindices vector: `{{0\uD83D\uDC48}, {} , {} , {}, {}, ....., {} , {}}`\n```\n**Iteration 2:**\n```\n \uD83D\uDC47\ns = "a a b * d * z d *"\n```\n```\nheap: `{a\uD83D\uDC48}` \nindices vector: `{{0,1\uD83D\uDC48}, {} , {} , {}, {}, ....., {} , {}}`\n```\n**Iteration 3:**\n```\n \uD83D\uDC47\ns = "a a b * d * z d *" \n```\n```\nheap: `{a\uD83D\uDC48,b}` \nindices vector: `{{0,1\uD83D\uDC48}, {2} , {} , {}, {}, ....., {} , {}}`\n```\n**Iteration 4 (star change):**\n```\n \uD83D\uDC47\ns = "a a b * d * z d *"\n \uD83D\uDC46(top of the min heap, remove "1" from iv)\n```\nNow, `s = "a ! b * d * z d *" `\n```\nheap: `{a\uD83D\uDC48, b}` \nindices vector: `{{0\uD83D\uDC48}, {2} , {} , {}, {}, ....., {} , {}}`\n```\n**Iteration 5:**\n```\n \uD83D\uDC47\ns = "a ! b * d * z d *"\n```\n```\nheap: `{a\uD83D\uDC48, b, d}` \nindices vector: `{{0\uD83D\uDC48}, {2} , {} , {4}, {}, ....., {} , {}}`\n```\n**Iteration 6 (star change):**\n```\n \uD83D\uDC47\ns = "a ! b * d * z d *"\n \uD83D\uDC46(top of the min heap, remove "0" from iv, remove "a" from heap)\n```\nNow, `s = "! ! b * d * z d *" `\n```\nheap: `{b\uD83D\uDC48, d}` \nindices vector: `{{}, {2\uD83D\uDC48} , {} , {4}, {}, ....., {} , {}}`\n```\n**Iteration 7:**\n```\n \uD83D\uDC47\ns = "! ! b * d * z d *"\n```\n```\nheap: `{b\uD83D\uDC48, d, z}` \nindices vector: `{{}, {2\uD83D\uDC48} , {} , {4}, {}, ....., {} , {6}}`\n```\n**Iteration 8:**\n```\n \uD83D\uDC47\ns = "! ! b * d * z d *"\n```\n```\nheap: `{b\uD83D\uDC48, d, z}` \nindices vector: `{{}, {2\uD83D\uDC48} , {} , {4,7}, {}, ....., {} , {6}}`\n```\n**Iteration 9 (star change):**\n```\n \uD83D\uDC47\ns = "! ! b * d * z d *"\n \uD83D\uDC46(top of the min heap, remove "2" from iv, remove "b" from heap)\n```\nNow, `s = "! ! ! * d * z d *"`\n```\nheap: `{d\uD83D\uDC48, z}` \nindices vector: `{{}, {} , {} , {4,7\uD83D\uDC48}, {}, ....., {} , {6}}`\n```\n**Iteration Complete:**\n```\ns = "! ! ! * d * z d *"\n \uD83D\uDC46(top of the min heap and indices vector, when we finish)\n```\nNow that we finished iterating thru the charachters, filter __!__ and __*__, the resultant string is `d z d`.\n\nFinal __states__ are:\n```\nheap: `{d\uD83D\uDC48, z}` \nindices vector: `{{}, {} , {} , {4,7\uD83D\uDC48}, {}, ....., {} , {6}}`\n```
53
2
['Heap (Priority Queue)', 'C++', 'Java', 'Python3']
9
lexicographically-minimum-string-after-removing-stars
O(N * 26) | Simple Greedy Solution | C++ | Java | Python
on-26-simple-greedy-solution-c-java-pyth-q37v
Approach -\n- When ever we encounter \'*\' , we need to remove the smallest character on the left of \'*\' \n- The Problem rises when there are multiple occur
Jay_1410
NORMAL
2024-06-02T04:10:42.585110+00:00
2024-06-02T04:41:50.762455+00:00
4,141
false
# Approach -\n- When ever we encounter `\'*\'` , we need to remove the smallest character on the left of `\'*\'` \n- The Problem rises when there are multiple occurences of smallest character \n- Here we can `greedily remove the rightmost occurence of the smallest character` on the left of `\'*\'` \n- This is because , removing the smallest character at any other postion , might pull the larger characters to the left , which will not be lexicographically smallest.\n# Code Explanation - \n- `Buckets` - of size 26 to keep track of positions of each character\n- `Removed` - For marking positions of removed characters\n- Whenever we find ` \'*\' ` , we will remove (mark as removed) the rightmost occurence of smallest character\n- Else we\'ll keep updating buckets for each character.\n- Finally we construct our resultant string using Removed array\n# Complexity - \n- Time Complexity - O(N * 26)\n- Space Complecity - O(N)\n```C++ []\nclass Solution {\npublic:\n string clearStars(string s){\n int n = s.size();\n vector<vector<int>> buckets(26);\n vector<int> removed(n , 0);\n for(int i = 0 ; i < n ; i++){\n if(s[i] == \'*\'){\n removed[i] = 1;\n for(int j = 0 ; j < 26 ; j++){\n if(buckets[j].size()){\n removed[buckets[j].back()] = 1;\n buckets[j].pop_back();\n break;\n }\n }\n }\n else{\n buckets[s[i]-\'a\'].push_back(i);\n }\n }\n string ans;\n for(int i = 0 ; i < n ; i++){\n if(!removed[i]) ans.push_back(s[i]);\n }\n return ans;\n }\n};\n```\n```Java []\n\nclass Solution {\n public String clearStars(String s){\n int n = s.length();\n \n List<List<Integer>> buckets = new ArrayList<>();\n \n for(int i = 0; i < 26; i++){\n buckets.add(new ArrayList<>());\n }\n \n boolean[] removed = new boolean[n];\n \n for (int i = 0 ; i < n ; i++){\n if(s.charAt(i) == \'*\'){\n removed[i] = true;\n for (int j = 0; j < 26; j++){\n if (!buckets.get(j).isEmpty()){\n removed[buckets.get(j).get(buckets.get(j).size() - 1)] = true;\n buckets.get(j).remove(buckets.get(j).size() - 1);\n break;\n }\n }\n } \n else{\n buckets.get(s.charAt(i) - \'a\').add(i);\n }\n }\n \n StringBuilder ans = new StringBuilder();\n for(int i = 0 ; i < n ; i++){\n if(!removed[i]) ans.append(s.charAt(i));\n }\n return ans.toString();\n }\n}\n\n```\n```Python []\nclass Solution:\n def clearStars(self, s: str) -> str:\n n = len(s)\n buckets = [[] for _ in range(26)]\n removed = [False] * n\n \n for i in range(n):\n if s[i] == \'*\':\n removed[i] = True\n for j in range(26):\n if buckets[j]:\n removed[buckets[j].pop()] = True\n break\n else:\n buckets[ord(s[i]) - ord(\'a\')].append(i)\n \n result = []\n for i in range(n):\n if not removed[i]:\n result.append(s[i])\n \n return \'\'.join(result)\n```\n
42
1
['Greedy', 'C++', 'Java', 'Python3']
10
lexicographically-minimum-string-after-removing-stars
Explained with thought process - Using min heap || Very simple
explained-with-thought-process-using-min-wy6r
Thought process\n- We need to find the smallest char towrds left of a given \' \'. This is some what close to smallest item towrds left which can be solved by s
kreakEmp
NORMAL
2024-06-02T04:04:27.393071+00:00
2024-06-02T05:00:51.731541+00:00
2,522
false
# Thought process\n- We need to find the smallest char towrds left of a given \'* \'. This is some what close to smallest item towrds left which can be solved by stack. But here we need to remove it and if we find another * then we need to delete the second smallest char and this is not possible using stack, as stack only track the one smallest item towards left. So I discarded this approach.\n- Next thought -> as we need to find all smallest items => basically we need to have a sorted list of all items from where we can fetch the smallest char in o(1). This can be done in two way -> add to a vector sort it each time or use a min heap where we always have the smallest item at the top. Min heap is the better option here as we don\'t have to access in between item but need to use the top item. This way problem is almost solved. \n- Now only two task pending is to handle the char of same type and char removal/final ans string generation. \n - To handle the same type of characters case -> we simply write a comparator and the one highest insed will be at the top\n - To genereate the string, its difficult to do it while we are finding the smallest one. As we need to remove one by one char each time which is a bit tidious process. So to solve this what we can do is to first mark the smallest chars while processing with a special character and later we can iterate and just skip out the special char from the final string. Again the special char can be any thing but as we have to remove * as well from the string we will select the special character as *. \n\n# Intuition\n- In place of deleting the smallest chars and \'* \' , we first identify the smallest char and replace it with \'* \' and finally only take out non \'* \' chars as answer.\n- To find out the smallest chars till a \'* \' we need to store all visited chars in a min heap along with the index. Inedx is needed to replace the original string char of that index to \'* \'\n\n# Approach\n- Create a min heap (priority queue) that stores the visited chars and its index in a pair\n- In the min heap the items are stored as smallest char appear at the top and if two chars are equal then we will keep the largest index at the top as that need to be removed first to achieve lexicographically smallest string\n- Now iterate over the string, \n - if the char is not \'*\' then simply add it along with its index in to the min heap\n - if the char is \'*\' then find the top element of the heap ( that is the smallest char with largest index when equal) and the idexed stored in the top is to be replaced by a \'*\' char in the actual string.\n- Finally, iterate one more time over string and now only take the non \'*\' chars in the ans variable\n\n# Complexity\n- Time complexity : O(N.logN)\n- Space complexity : O(N)\n\n# Code\n```\nstring clearStars(string s) {\n auto comp = [](const pair<int, int>& a, const pair<int, int>& b){ //comparator to sort in priority queue\n if(a.first == b.first) return a.second < b.second;\n return a.first > b.first;\n };\n priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comp)> pq;\n string ans = "";\n for(int i = 0; i < s.size(); ++i){ \n if(s[i] != \'*\') { // when not \'*\' then simply push the ith char and index i to the priority queue\n pq.push({s[i], i}); \n }else{\n s[pq.top().second] = \'*\'; // when its \'*\', find the smallest index and rpelace that char with \'*\'\n pq.pop();\n }\n }\n for(auto c: s) (c != \'*\') && (ans += c); // take all chars as ans except the \'*\' chars\n \n return ans;\n}\n```\n\n\n\n---\n\n<b>Here is an article of my last interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted\n\n---\n
28
1
['C++']
14
lexicographically-minimum-string-after-removing-stars
Rightmost Smallest
rightmost-smallest-by-votrubac-n35v
For each star, we need to remove the rightmost instance of the smallest character.\n\nTo do that, we store positions of each character in pos as we go left to r
votrubac
NORMAL
2024-06-02T04:03:36.263396+00:00
2024-06-06T21:25:40.213478+00:00
926
false
For each star, we need to remove the rightmost instance of the smallest character.\n\nTo do that, we store positions of each character in `pos` as we go left to right.\n\nWhen we see a star:\n- Find the smallest available character.\n\t- We can do it by iterating through 26 characters, or use a set or a heap.\n- Change the last position of that characer in `s` to `*`.\n- Remove the last position from `pos`.\n\nFinally, we remove all star characters, and return the string.\n\nThe complexity of this solution is O(26 n) for the simple iteration, and O(n log 26) for the set/heap.\n\nHowever, the runtime seems to favor the simple iteration:\n- Simple iteration: 80 ms\n- Set: 150 ms\n- Heap: 120 ms\n\nThis is, perhaps, because 26 is small enough number, and the set/heap add some overhead:\n\n### Simple Iteration\n**C++**\n```cpp\nstring clearStars(string s) {\n array<vector<int>, 26> pos;\n for (int i = 0; i < s.size(); ++i)\n if (s[i] == \'*\')\n for (auto &p : pos) {\n if (!p.empty()) {\n s[p.back()] = \'*\';\n p.pop_back();\n break;\n }\n }\n else\n pos[s[i] - \'a\'].push_back(i);\n erase(s, \'*\');\n return s;\n}\n```\n\n### Set\n**C++**\n```cpp\nstring clearStars(string s) {\n set<int> sm;\n array<vector<int>, 26> pos;\n for (int i = 0; i < s.size(); ++i)\n if (s[i] == \'*\') {\n while (pos[*begin(sm)].empty())\n sm.erase(begin(sm));\n s[pos[*begin(sm)].back()] = \'*\';\n pos[*begin(sm)].pop_back();\n }\n else {\n pos[s[i] - \'a\'].push_back(i);\n sm.insert(s[i] - \'a\');\n }\n\terase(s, \'*\');\n return s;\n}\n```\n\n### Heap\n**C++**\n```cpp\nstring clearStars(string s) {\n priority_queue<int, vector<int>, greater<int>> sm;\n array<vector<int>, 26> pos;\n for (int i = 0; i < s.size(); ++i)\n if (s[i] == \'*\') {\n while (pos[sm.top()].empty())\n sm.pop();\n s[pos[sm.top()].back()] = \'*\';\n pos[sm.top()].pop_back();\n }\n else {\n if (pos[s[i] - \'a\'].empty())\n sm.push(s[i] - \'a\');\n pos[s[i] - \'a\'].push_back(i);\n }\n erase(s, \'*\');\n return s;\n}\n```
20
3
['C']
5
lexicographically-minimum-string-after-removing-stars
Dekh 👁️ rha hai Vinod 🤦‍♂️ Solve kr liya 😂 || Hindi 🔥 Explanation || C++ Solution
dekh-rha-hai-vinod-solve-kr-liya-hindi-e-gcgw
Intuition\n Describe your first thoughts on how to solve this problem. \n sab milega code me milega\n# Approach\n Describe your approach to solving the problem.
abhirai1
NORMAL
2024-06-02T04:27:47.307995+00:00
2024-06-02T11:35:30.690666+00:00
664
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* sab milega code me milega\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* code me approach lelo, approach lelo\n\n# Complexity\n* Time Complexity:- O(n log n)\n* Space Complexity:- O(n)\n# Code\n```\n\nclass Solution {\npublic:\n \n \n/*\nAakhir es que me jo bola hai, uska matlab huaa, * ke nearest ka minimum element jo bhi ho use delete kr do\n\nClear statement nhi lga(aao samjhata hu)\n\n(......................)*\nye dot * ke aane ke pehle ka subarray hai thik,\nto hme sabse minimum choose krna hai, character ko.\n\nto tum bologe Abhishek bhai, to phir sidhe bolane ka n, ye complex karke kyu bola tumne\n* ke nearest ka minimum element jo bhi ho\n\nGajab ho tum Abhishek bhai, aasan rakhne ka, complex kar rhe faltu ka\n\nArey bhai thamba thamba, dekho dekho aise bolna jaruri hai kyuki\n\naao dikhata hu\n\n(aaba)*\nto kaun sa a htavoge, es range me to minimum a hai, bolo bolo\narey bolte kyu nhi..\n\nSamjhe to jo minimum elements hai, usme jo sabse pass hai * ke usko htana hai\n\nto tum keh rhe abhishek bhai ye to complex lag rha,\narey tumhara bhai, rumhare sath hai chinta nhi karne ka, aasan karna mera kaam\n\n(.....................) *\n\nachcha to hme koi aisa jadu karna hai, jisse ki hme use dot dot ka minimum element mil jaye\n\nAudience be like :- mai samjh gya, mai samjh gya \nmai ya to (minPQ, multiset) use kr lunga\n\nthik thik hai, ruk jao itna khush mat hovo\n\nminPQ me vo element top me hoga jiski value minimum hogi.\nAudience:- ekdam thik bola tumne\nAbhishek:- achcha ek baat btavo minPQ kya karta hai jab same element hota hai.\n\nAudience:- Aaye...e ka bol diye, dekh rha hai binod, tej ban rha hai\n\nAbhishek:- guss na hoiye malik, achcha ek baat hai mai PQ me index ke sath elment ko rakhuga\nAudience:- kyu, terese aasani se kaam nhi hota kaa..\nAbhishek:- arey pop karte time kaise pta chalega ki kaun sa element huaa hai\n\nAudience:- thik hai thik hai, ham samjh gye the, tumhara knowledge check kr rhe the, aati hi hai ya bas bolte ho\n\nAbhishek:- thik to agree karte ho index ko sath rakhna hai character ke, thik. achcha ek baat btavo agar mai ind bhi rakha hai aur\n do character hai same hai to top pe kaun hoga \n string => caa*\n Que time :- {a,1},{a,2};\n to top pe kaun hoga ? {a,1} ya {a,2}=> {a,1} n ye to fash gye\n \n Audience dar gyi Audience dar gyi \n \nab bolo binod.\n\nAudience:- be like, ka bawasir que hai, ek chij socho ek chij pe fash jaoo\n\nAbhishek:- dekho agr kaisa ho ki first value min ho and second value maximum agr vo top pe aa jaye to mza hi aa jaye\n\nAudience:- e kaise hoga\n\nAbhishek:- bole to comperator se bhaiya\n\n mazak se hat ke, agr comperator se familiar nhi ho to YT pe video dekh lena(comperator ki, kisi aur ki mat dekhna)\n \n \nbas que khatam, * aaye PQ ke top ko pop karo and kaam khatam.\nLekin ek minute aakhir tum answer wala string kab banaoge\n\ndekho jab jab jo pop hoga, uski index mark kar dunga, phir pura traverse krke, unmark ind ko add kr dunga simple hai simple hai\n\nAudience:- Samjh aa gya, tere explanation me daam nhi th, hmare dimak me daam hai \n\n\nAgr doubt hai to feel free to ask in comment section, baaki milte hai kabhi...dusari post me \n*/\n \n \n struct Compare {\n bool operator()(const pair<int, int>& a, const pair<int, int>& b) {\n if (a.first == b.first)\n return a.second < b.second; \n return a.first > b.first; \n }\n };\n \n string clearStars(string s) {\n int n=s.size();\n string ans="";\n\n // ascii code to suna hi hoga tumne\n priority_queue<pair<int, int>, vector<pair<int, int>>, Compare> pq;\n\n // hint bina comperator ke possible hai, if tum index ko\n // -1 se multiply krke push kro, minPQ me to\n // vis[ind] krte time, abs le lena bas(try krke dekh lo)\n \n vector<int> vis(n,0);\n \n for(int i=0;i<n;i++){\n if(s[i]==\'*\'){\n // jo pop visit kar diya\n vis[pq.top().second]=1;\n pq.pop();\n \n // ye star ko visit kar rha, vo to answer ka hissa hoga hi nhi\n vis[i]=1;\n }else{\n // ascii ka kamal\n pq.push({s[i],i});\n }\n }\n \n for(int i=0;i<n;i++){\n // jo visit nhi vo answer me jayega\n if(vis[i]==0){\n ans.push_back(s[i]);\n }\n }\n \n return ans;\n }\n};\n```
19
1
['Heap (Priority Queue)', 'C++']
7
lexicographically-minimum-string-after-removing-stars
Using Heap | Python
using-heap-python-by-pragya_2305-snsc
Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(n)\n\n# Code\n\nclass Solution:\n def clearStars(self, s: str) -> str:\n heap = []\n
pragya_2305
NORMAL
2024-06-02T04:18:00.232087+00:00
2024-06-02T05:49:58.570131+00:00
848
false
# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def clearStars(self, s: str) -> str:\n heap = []\n for i,c in enumerate(s):\n if c==\'*\':\n heappop(heap)\n else:\n heappush(heap,(c,-i))\n \n ans = [\'\']*len(s)\n while heap:\n char,i = heappop(heap)\n ans[-i] = char\n \n return \'\'.join(ans)\n \n \n```
14
1
['String', 'Heap (Priority Queue)', 'Python', 'Python3']
3
lexicographically-minimum-string-after-removing-stars
C++ || Priority Queue || Custom Comparator
c-priority-queue-custom-comparator-by-ab-4mln
Connect with me on LinkedIn: https://www.linkedin.com/in/abhay5349singh/\n\nApproach:\n build custom comparator based on given requirements\n\t if 2 char are sa
abhay5349singh
NORMAL
2024-06-02T04:02:45.527777+00:00
2024-06-02T04:02:45.527812+00:00
932
false
**Connect with me on LinkedIn**: https://www.linkedin.com/in/abhay5349singh/\n\n**Approach:**\n* build custom comparator based on given requirements\n\t* if 2 char are same, we will delete char present at max index \n\t* for distinct char, we will delete lestfmost smallest\n* maintaining `priority queue` to access most suitable char for deletion at top\n\n```\nclass Solution {\npublic:\n \n struct node{\n char ch;\n int idx;\n };\n \n struct compare{\n bool operator()(const node &a, const node &b){\n if(a.ch == b.ch) return a.idx < b.idx; // max heap\n return a.ch > b.ch; // min heap\n }\n };\n \n string clearStars(string s) {\n int n = s.length();\n \n priority_queue<node,vector<node>,compare> pq;\n for(int i=0;i<n;i++){\n char ch = s[i];\n if(ch==\'*\'){\n if(pq.size() > 0) pq.pop();\n }else{\n pq.push({ch, i});\n }\n }\n \n vector<pair<int,char>> v;\n while(pq.size() > 0){\n node cur = pq.top();\n pq.pop();\n \n v.push_back({cur.idx, cur.ch});\n }\n\t\t\n sort(v.begin(), v.end()); // since we need to maintain orginal indexing of chars in string\n \n string ans = "";\n for(pair<int,char> p : v) ans += p.second;\n \n return ans;\n }\n};\n```\n\n**Do upvote if it helps :)**
10
3
[]
3
lexicographically-minimum-string-after-removing-stars
Min heap with smallest (char + index) pairs.
min-heap-with-smallest-char-index-pairs-n9sa5
Intuition and approach:\nQuestion wants me to delete chars from a string, first thing I think about is creating a stringbuilder because strings are immutable. \
codingtosh
NORMAL
2024-06-02T04:47:45.564249+00:00
2024-06-03T14:16:39.311736+00:00
538
false
# Intuition and approach:\nQuestion wants me to delete chars from a string, first thing I think about is creating a stringbuilder because strings are immutable. \n\nNow, even deleting from stringbuilder takes O(n) unless we remove from the end all the time(which we arent),\n\nso, instead of deleting, just replace the char with some non-alphabet like \'.\' \n\nWe can at the end, create a new stringbuilder by appending all the chars(except the \'.\') in this above mentioned stringbuilder to get the answer.\n\nGreat, now we just need to figure out how to delete the smallest alphabet on the left of *. The question says we can delete any smallest char occurence from the left of *. \n\nSo what now? Do we create possible permutations of such removals and then memoize them with backtracking along with pruning and sending a space shuttle to proxima centauri?\n\nNo, that will be going overboard. We need to make the smallest lexicographical(dictionary order) string.\n\nSo why would we remove the smallest index of that smallest character? Take for instance, acbasd* , if we remove first a, we get cbasd and if we remove the second a(closest to *), we get acbsd. \n\nWhich one is smaller lexicographically? Which one occurs in the dictionary first? acbsd or cbasd? It is acbsd. This illustrates we need to remove the "closest" to * or in other words, the biggest index of the said character.\n\nWe can start iterating from the beginning of our str. If we encounter \'*\' we now want to "delete" the closest smallest alphabet to its left. \n\nWe can simply just do that with a while loop, start iterating to its left and keep track of min char index. Once you have that index after reaching the 0 index, just set a \'.\' on that index. But this whole thing is O(n) operation at the worst case. \n\nWhich means, our total run time will be O(n^2). We look at the constraints, and figure we cant really do with this. It will likely give us TLE because 10^5 is the max len of the input string. 10^5^2 is 10^10 which is highly likely TLE.\n\nWe ask ourselves, why do I need to keep searching the same space again and again, can I somehow track the order in some auxillary data structure?\n\nThis is where minHeap comes into the picture.\n\nMin heap sorts the elements as it is inserting them. Creating an n sized heap takes n logn time because each insertion makes logn comparisons to bubble up the min element to the top.\n\nTo fetch the min element, we can poll the heap, which returns its top most element after removing it from the heap in logn again. It takes logn time again because the root is removed, it now has to figure out a new root by comparing the children at each level of the tree(heap), which has logn height. \n\nSo now we create a min heap of int[] where int[] contains char(the ASCII val represented in int) at [0] and its index at [1]. We traverse our str, keep adding to the heap all the non *. It keeps getting sorted inherently....right? Not really.\n\nHeaps require a comparator to understand how we want to sort out the preexisting elements in it as we insert a new one(ore remove from it). For that, we create a comparator which takes both children nodes being compared (int[] a and int[] b) and call Integer.compare on their ASCII values. \n\nThis should work right? It wont. Lets say we have [a, 4] already inserted and [a, 1] as the new insertion.\n\n[a, 1] will actually get bubbled up to the top because we only told the program to compare char ASCII values, nothing about the index. While [a,1] is indeed the smallest char, it isnt the "closest" one to *. \n\nSo we need to be careful here and specify that we want to compare indices in case ASCII values are equal, and bubble the BIGGEST index to the top. \n\nGreat, so far so good. We have a heap that keeps increasing as we keep traversing the string with the smallest character closest to * on the top.\n\nWhenever we encounter *, we simply first set \'.\' to replace * and then we poll our heap which gives us the smallest char closest to the left of *. We will simply set a \'.\' over there as well. \n\nSo now is everything gucci? Wait...we are polling a heap, what if it has nothing to poll? What if we encounter a * before we got a chance to find alphabets? Or what if a series of **** is bigger than the current size of our heap?\n\nThat\'s a bummer, do we need to then do null checks here? That\'s a pain. Wait...lets read the description again. \n\nIt is guaranteed that -->\nThe input is generated such that it is possible to delete all \'*\' characters.\n\nWe read this and first we thank our leetcode Gods that they showed kindness to us as they drive their lambo into the sunset while we have to grind problems on their website to afford basic housing. Then we move back to the problem.\n\nIn other words, there wont ever be * with no alphabets to its left, so our heap is ALWAYS non empty, meaning we can poll from it without worrying about NPEs(null pointer exceptions).\n\nThat\'s it, it should work. We\'ll just create an output string by appending all the non \'.\' \n \n\n# Complexity\n- Time complexity: O(nlogn) : logn per insertion/removal, total n elements in the worst case. so n*logn total.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n) : heap and output string will hold n elements in the worst case(think no * in the input string at all), O(n+n) = O(2n) = O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String clearStars(String s) {\n StringBuilder str = new StringBuilder(s);\n PriorityQueue<int[]> q = new PriorityQueue<>((int[] a, int[] b) -> {\n int charComparison = Integer.compare(a[0], b[0]);\n if (charComparison != 0) {\n return charComparison;\n }\n // If characters are equal, compare their indices instead \n // so pq doesnt bubble the wrong element to the top based on char alone\n // we\'d want smallest char with the smallest index on the top. \n return Integer.compare(b[1], a[1]); \n });\n for(int i = 0; i < str.length(); i++){\n if(str.charAt(i) == \'*\'){\n str.setCharAt(i, \'.\'); //removing *\n int left = i-1;\n //delete the closest left smallest non * by putting . there\n int smallestLeftCharIndex = (q.poll())[1]; //logn operation\n /********************************************************\n * this would have given you TLE, *\n * instead of polling pq, you\'re looking for the index * \n * which is O(n), making overall O(n^2) *\n *********************************************************/\n // char smallestLeftChar = \'Z\';\n // int smallestLeftCharIndex = left;\n // while(left >= 0){\n // char currLeftChar = str.charAt(left);\n // if(currLeftChar < smallestLeftChar){\n // smallestLeftChar = currLeftChar;\n // smallestLeftCharIndex = left;\n // }\n // left--;\n // }\n str.setCharAt(smallestLeftCharIndex, \'.\');\n left--;\n \n }else{\n //logn operation\n //do it n times in the worst case, overall, O(nlogn)\n q.add(new int[]{s.charAt(i), i});\n }\n }\n StringBuilder ans = new StringBuilder();\n for(int i = 0; i < str.length(); i++){\n if(str.charAt(i) != \'.\'){\n ans.append(str.charAt(i));\n }\n }\n return ans.toString();\n }\n}\n```
9
1
['String', 'Heap (Priority Queue)', 'Java']
3
lexicographically-minimum-string-after-removing-stars
O(n) solution optimized!!
on-solution-optimized-by-resilientwarrio-xu5u
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\n# Complexity\n- Tim
ResilientWarrior
NORMAL
2024-06-02T10:19:20.618885+00:00
2024-06-02T10:19:20.618905+00:00
71
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\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nworest case: O(3n) - if s consists of only \'*\'\nO(3n) = O(n) hence the overall time complexity is O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution:\n def clearStars(self, s: str) -> str:\n\n # index is a dictionry that stores the index of each character seen \n index = defaultdict(list)\n ast_index = [] # ast_index is used to store index of "*" seen \n deleted = set()\n \n for i, char in enumerate(s): \n \n if char != \'*\': \n index[char].append(i)\n else: \n if ast_index: \n deleted.add(ast_index.pop())\n \n if index: \n small = min(index)\n \n deleted.add(index[small].pop())\n \n if not index[small]: \n del index[small]\n \n ast_index.append(i)\n \n \n stack = []\n for i in range(len(s)): \n \n if s[i] != \'*\' and i not in deleted: \n stack.append(s[i])\n \n return \'\'.join(stack)\n \n \n```
8
0
['Python3']
0
lexicographically-minimum-string-after-removing-stars
[Python3] priority queue
python3-priority-queue-by-ye15-l259
Please check out this commit for solutions of weekly 400 in C++, Java, Python, Javascript, Typescript. \n\n\nclass Solution:\n def clearStars(self, s: str) -
ye15
NORMAL
2024-06-02T04:50:32.984072+00:00
2024-06-02T05:04:21.546285+00:00
160
false
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/bff6a0f3ec96f274af106541d85a4c48c6a0af82) for solutions of weekly 400 in C++, Java, Python, Javascript, Typescript. \n\n```\nclass Solution:\n def clearStars(self, s: str) -> str:\n s = list(s)\n pq = []\n for i, ch in enumerate(s): \n if ch == \'*\': s[-heappop(pq)[1]] = \'*\'\n else: heappush(pq, (ch, -i))\n return \'\'.join(s).replace(\'*\', \'\')\n```
8
0
['Python3']
0
lexicographically-minimum-string-after-removing-stars
Hash Table || O(N*26)
hash-table-on26-by-thiennk-q51s
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
Thiennk
NORMAL
2024-06-02T05:02:38.620503+00:00
2024-06-11T10:19:31.853440+00:00
122
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*26)\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 fun clearStars(str: String): String {\n var s: MutableList<Char> = mutableListOf()\n for (i in str) s.add(i);\n var a: MutableList<MutableList<Int>> = MutableList(123) {mutableListOf()}\n for (i in 0 until s.size) {\n if (s[i] != \'*\')\n a[s[i].code].add(i);\n else {\n for (j in 97..122) {\n if (a[j].size > 0) {\n s[a[j][a[j].size - 1]] = \'.\'\n a[j].removeAt(a[j].size-1);\n break;\n }\n }\n }\n }\n var rs = "";\n for (i in s)\n if (i != \'*\' && i != \'.\')\n rs += i;\n return rs;\n }\n}\n```
6
0
['Hash Table', 'Kotlin']
0
lexicographically-minimum-string-after-removing-stars
C++ | Easy to Understand | Step By Step Expl
c-easy-to-understand-step-by-step-expl-b-26cr
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem asks us to remove asterisks (\'\') from a string while preserving the
VYOM_GOYAL
NORMAL
2024-06-02T04:01:21.918553+00:00
2024-06-02T04:01:21.918595+00:00
872
false
![Zombie Upvote.png](https://assets.leetcode.com/users/images/46981039-92a0-4676-8a5c-8be857ac654d_1717300873.1417475.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem asks us to remove asterisks (\'*\') from a string while preserving the lexicographically smallest possible result. We can achieve this by iterating through the string and considering two cases:\n\n1. **Non-asterisk character (s[i] != \'*\'):**\n - We add the character and its index to a priority queue (pq). Here, the priority is defined such that characters with the same value are ordered with larger indices coming first (ensuring we remove the rightmost occurrence if necessary). When a smaller character is encountered later, it will take precedence in the queue.\n2. **Asterisk character (s[i] == \'*\'):**\n - We remove the leftmost non-asterisk character from the queue using pq.top(). This character represents the smallest non-asterisk encountered so far, and we mark its position in the string with another asterisk (s[it.second] = \'*\'), effectively deleting it.\nBy systematically removing the leftmost asterisk and the smallest non-asterisk character to its left, we gradually transform the string into the lexicographically smallest form without asterisks.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Priority Queue:** We employ a priority queue (pq) to store pairs of characters and their corresponding indices. The prioritization criteria are:\n - If characters are the same, the pair with the larger index has higher priority (ensuring rightmost non-asterisk characters are considered first).\n - If characters are different, characters with a smaller value have higher priority (guaranteeing the removal of the smallest non-asterisk character).\n2. **Iterate and Process: We iterate through the string (s):**\n - **If the current character is not an asterisk (s[i] != \'*\'):**\n - Push the character-index pair ({s[i], i}) onto the priority queue.\n - **If the current character is an asterisk (s[i] == \'*\'):**\n - Pop the top element (it) from the priority queue. This represents the smallest non-asterisk character encountered so far.\n - Mark the position of this character in the string with another asterisk (s[it.second] = \'*\'), effectively deleting it.\n \n3. **Remove Asterisks:** After processing the entire string, we use std::remove to remove all remaining asterisks from s.\n\n# Complexity\n- Time complexity: **O(n * log n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(n)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n string clearStars(string s) {\n int n = s.size();\n \n // PQ to store pairs (character, index)\n // Custom to get smallest character but largest index\n auto comp = [](const pair<char, int>& a, const pair<char, int>& b) {\n if (a.first == b.first) {\n return a.second < b.second; // larger index pehle ayega\n }\n return a.first > b.first; // smaller character pehle ayega\n };\n \n priority_queue<pair<char, int>, vector<pair<char, int>>, decltype(comp)> pq(comp);\n\n\n for (int i = 0; i < n; ++i) {\n if (s[i] != \'*\') {\n pq.push({s[i], i});\n } else {\n auto it = pq.top();\n pq.pop();\n s[it.second] = \'*\';\n }\n }\n\n s.erase(std::remove(s.begin(), s.end(), \'*\'), s.end());\n \n return s;\n }\n};\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```
6
1
['String', 'Heap (Priority Queue)', 'C++']
4
lexicographically-minimum-string-after-removing-stars
Heaps based approach to solve this easily...
heaps-based-approach-to-solve-this-easil-obo5
\n\n# Code\n\nclass Solution:\n def clearStars(self, s: str) -> str:\n heap = []\n for i,c in enumerate(s):\n if c==\'*\':\n
Aim_High_212
NORMAL
2024-06-02T05:41:59.766788+00:00
2024-06-02T05:41:59.766811+00:00
42
false
\n\n# Code\n```\nclass Solution:\n def clearStars(self, s: str) -> str:\n heap = []\n for i,c in enumerate(s):\n if c==\'*\':\n heappop(heap)\n else:\n heappush(heap,(ord(c),-i))\n \n ans = [\'\']*len(s)\n while heap:\n ordChar,i = heappop(heap)\n ans[-i] = chr(ordChar)\n \n return \'\'.join(ans)\n \n \n```
4
0
['Python', 'Java', 'Python3']
0
lexicographically-minimum-string-after-removing-stars
Easy to Understand | using Priority queue🔥✅ | No Custom Comparator
easy-to-understand-using-priority-queue-zikau
Approach\n\n\nIn this problem, we need to remove characters from a string s whenever a * is encountered. Specifically, each * character should remove the smalle
arunava_42
NORMAL
2024-06-02T04:34:29.146082+00:00
2024-06-08T18:50:55.504758+00:00
205
false
# Approach\n\n\nIn this problem, we need to remove characters from a string `s` whenever a `*` is encountered. Specifically, each `*` character should remove the smallest character that appears before it. If there are multiple smallest characters, we remove the nearest one to the `*`.\n\nTo solve this, we can use a min-heap (priority queue) to efficiently manage the characters and their positions in the string. Here is a step-by-step guide to understanding and implementing the solution:\n\n### Step-by-Step Solution\n\n1. **Min-Heap Usage**:\n - We use a min-heap to keep track of characters and their positions. By storing the positions as negative values, we can ensure that the most recent occurrence of the smallest character is prioritized when popping from the heap.\n\n2. **First For-Loop**:\n - Traverse the string `s`.\n - For each non-star character, push it onto the min-heap along with its position (multiplied by -1).\n - For each \'*\' character, pop the top element from the min-heap. This removes the smallest character that appears closest to the \'*\'.\n\n3. **Maintaining Valid Indices**:\n - After processing the entire string, the min-heap will contain only the characters that have not been removed by any \'*\'.\n - Transfer the indices of these remaining characters into a set (`validIndices`). This set helps us quickly check which characters should be included in the final result.\n\n4. **Second For-Loop**:\n - Traverse the string `s` again.\n - Construct the result string by including only those characters whose indices are present in the `validIndices` set.\n\n### Example Walkthrough\n\nLet\'s consider an example string `s = "abc*de*f*g"`:\n\n1. **Initial Traversal and Min-Heap Operations**:\n - \'a\' is added to the min-heap.\n - \'b\' is added to the min-heap.\n - \'c\' is added to the min-heap.\n - \'*\' is encountered, the smallest character (\'a\') is removed from the min-heap.\n - \'d\' is added to the min-heap.\n - \'e\' is added to the min-heap.\n - \'*\' is encountered, the smallest character (\'b\') is removed from the min-heap.\n - \'f\' is added to the min-heap.\n - \'*\' is encountered, the smallest character (\'c\') is removed from the min-heap.\n - \'g\' is added to the min-heap.\n\n2. **Final State of the Min-Heap**:\n - The min-heap now contains \'d\', \'e\', \'f\' and \'g\'.\n\n3. **Transfer to Set**:\n - The set `validIndices` will have the indices corresponding to \'d\', \'e\', \'f\' and \'g\' (i.e., 4, 5,7 and 9).\n\n4. **Constructing the Result String**:\n - Traverse `s` again and include only those characters whose indices are in `validIndices`.\n - The final result is `"defg"`.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: `O(nlogn)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(n)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n priority_queue<pair<char, int>, vector<pair<char, int>>, greater<pair<char, int>>> charQueue; \n for (int i = 0; i < s.size(); i++) {\n if (s[i] != \'*\') {\n charQueue.push({s[i], -i}); \n } else if (s[i] == \'*\') {\n charQueue.pop();\n }\n }\n \n set<int> validIndices;\n while (!charQueue.empty()) {\n validIndices.insert(-charQueue.top().second);\n charQueue.pop();\n }\n \n string result = "";\n for (int i = 0; i < s.size(); i++) {\n if (validIndices.count(i)) {\n result += s[i];\n }\n }\n \n return result;\n }\n};\n\n```
4
1
['String', 'Heap (Priority Queue)', 'C++']
4
lexicographically-minimum-string-after-removing-stars
O(N) time and space solution. Simple and Easy to Understand
on-time-and-space-solution-simple-and-ea-xxhy
Track Positions : \n\n- As we scan the string from left to right, we\'ll keep track of the positions of each character in a dictionary called positions.\n\n---\
Guru_Prasath_K_S
NORMAL
2024-06-02T04:29:18.910731+00:00
2024-06-02T04:38:45.821347+00:00
48
false
# Track Positions : \n\n- As we scan the string from left to right, we\'ll keep track of the positions of each character in a dictionary called `positions`.\n\n---\n\n\n# Encounter a Star :\n\n- When we come across a star `*`, we need to identify the smallest character that is currently available.\n- We then change the character at the last recorded position of this smallest character to a star `*`.\n- After making the change, we remove this position from our positions dictionary.\n\n---\n\n\n\n# Clean Up : \n- Once we\'ve processed the entire string, we\'ll remove all star characters `*` from it.\n\n---\n\n\n# Return the Result : \n- The final string, with the rightmost instance of the smallest character removed, is returned.\n\n---\n\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n vector<vector<int>> positions(26);\n\n for(int i = 0 ; i < s.size() ; i++) {\n if(s[i] != \'*\') {\n positions[s[i] - \'a\'].push_back(i);\n } else {\n for(int j = 0 ; j < 26 ; j++) {\n if(!positions[j].empty()) {\n s[positions[j].back()] = \'*\';\n positions[j].pop_back();\n break;\n }\n }\n }\n }\n\n string result;\n\n for(int i = 0 ; i < s.size() ; i++) {\n if(s[i] != \'*\') {\n result += s[i];\n }\n }\n\n return result;\n }\n};\n```
4
0
['String', 'C++']
0
lexicographically-minimum-string-after-removing-stars
Python3 Dictionary solution
python3-dictionary-solution-by-chrehall6-hek3
Intuition\n Describe your first thoughts on how to solve this problem. \nBrute force solution is O(n^2), so we have to do better. We notice that, whenever there
chrehall68
NORMAL
2024-06-02T04:05:11.294085+00:00
2024-06-02T04:05:11.294113+00:00
162
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBrute force solution is O(n^2), so we have to do better. We notice that, whenever there are multiple occurrences of the "minimum letter", we always remove the rightmost one (guarantees the lexically least string after removal). So, we can store characters and the indexes at which we saw them. Whenever we see an asterisk, simply remove the rightmost occurrence of the minimum letter. Once we have iterated through the string, we just need to reconstruct the string using only the letters that we didn\'t remove.\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def clearStars(self, s: str) -> str:\n chars = {}\n for i in range(len(s)):\n if s[i] != "*":\n # store the letter\n if s[i] not in chars:\n chars[s[i]] = []\n\n chars[s[i]].append(i)\n\n else:\n # it\'s a star\n # find minimum letter so far\n min_letter = min(chars.keys())\n # we will remove that letter\n chars[min_letter].pop() # remove the rightmost one\n\n # remove letter if it no longer occurs\n if len(chars[min_letter]) == 0:\n del chars[min_letter]\n\n # reconstruct string\n reconstructed = ["" for _ in range(len(s))]\n for letter in chars:\n for idx in chars[letter]:\n reconstructed[idx] = letter\n return "".join(reconstructed)\n```
4
1
['Python3']
2
lexicographically-minimum-string-after-removing-stars
simple and easy C++ solution 😍❤️‍🔥
simple-and-easy-c-solution-by-shishirrsi-5hmg
if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n\nclass Solution {\npublic:\n string clearStars(string s) \n {\n int cnt = count(s.
shishirRsiam
NORMAL
2024-06-02T16:58:26.872303+00:00
2024-06-02T17:01:12.907375+00:00
73
false
# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) \n {\n int cnt = count(s.begin(), s.end(), \'*\');\n if(cnt+cnt == s.size()) return "";\n \n int n = s.size(), idx;\n map<char,vector<int>>mp;\n for(int i=0;i<n;i++)\n {\n char ch = s[i];\n if(ch==\'*\')\n {\n for(auto [c, vec]:mp)\n {\n if(vec.size()) \n {\n idx = vec.back();\n mp[c].pop_back();\n s[idx] = \'.\';\n break;\n }\n }\n }\n else mp[ch].push_back(i);\n }\n\n string ans;\n for(auto ch:s)\n {\n if(isalpha(ch))\n ans += ch;\n }\n return ans;\n }\n};\n```
3
0
['Hash Table', 'String', 'Sorting', 'C++']
3
lexicographically-minimum-string-after-removing-stars
Short & Simple Code | Only using Priority queue🔥✅ | No Custom Comparator
short-simple-code-only-using-priority-qu-z6cc
Approach\n Describe your approach to solving the problem. \n1. Initialization:\n - The priority queue pq is defined to store pairs of characters and their ind
Sachin___Sen
NORMAL
2024-06-02T14:15:12.646046+00:00
2024-06-02T14:15:12.646067+00:00
25
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Initialization**:\n - The priority queue `pq` is defined to store pairs of characters and their indices, ordered by the character in ascending order.\n\n2. **Processing the String**:\n - Iterate over the string `s`.\n - If the character is not `*`, push it along with its negative index into the priority queue.\n - If the character is `*`, pop the top element from the priority queue (i.e., the smallest character) and mark its position in `s` with `#`.\n\n3. **Building the Result**:\n - Traverse the modified string `s`, and construct a new string `ans` excluding all `#` and `*` characters.\n\nThis approach retains the same functionality but is more concise and clear, making it easier to understand.\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n priority_queue<pair<char,int>,vector<pair<char,int>>,greater<pair<char,int>>>pq;\n for(int i=0;i<s.length();i++){\n if(s[i]!=\'*\') pq.push({s[i],-i});\n else{\n char ch=pq.top().first;\n int idx=abs(pq.top().second);\n pq.pop();\n s[idx]=\'#\';\n }\n }\n string ans="";\n for(int i=0;i<s.length();i++){\n if(s[i]!=\'#\' && s[i]!=\'*\') ans.push_back(s[i]);\n }\n return ans;\n }\n};\n```
3
0
['C++']
0
lexicographically-minimum-string-after-removing-stars
🏆💢💯 Faster✅💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅💥🔥💫Explained☠💥🔥 Beats 💯
faster-lesser-cpython3javacpythonexplain-3xpf
Intuition\n\n\nC++ []\nclass Solution {\npublic:\n string clearStars(string s) {\n vector<vector<int>> have(26);\n for (int i = 0; i < s.length
Edwards310
NORMAL
2024-06-02T08:55:09.166069+00:00
2024-06-02T08:55:09.166103+00:00
107
false
# Intuition\n![0ehh83fsnh811.jpg](https://assets.leetcode.com/users/images/a5b828cc-3291-415b-8490-fa685171d463_1717318356.5716841.jpeg)\n![Screenshot 2024-06-02 142338.png](https://assets.leetcode.com/users/images/edd865cd-09b6-44ab-abea-35b30200aa7f_1717318435.5919673.png)\n```C++ []\nclass Solution {\npublic:\n string clearStars(string s) {\n vector<vector<int>> have(26);\n for (int i = 0; i < s.length(); ++i) {\n if (s[i] == \'*\') {\n for (int j = 0; j < 26; ++j) {\n if (!have[j].empty()) {\n have[j].pop_back();\n break;\n }\n }\n } else {\n have[s[i] - \'a\'].push_back(i);\n }\n }\n vector<pair<int, char>> v;\n for (int i = 0; i < 26; ++i) {\n const char c = i + \'a\';\n for (int x : have[i]) {\n v.push_back({x, c});\n }\n }\n sort(v.begin(), v.end());\n string r;\n for (const auto& p : v) {\n r.push_back(p.second);\n }\n return r;\n }\n};\n```\n```python3 []\nclass Solution:\n def clearStars(self, s: str) -> str:\n ans = \'\'\n curr = [0 for i in range(26)]\n for i in range(len(s)):\n if s[i] == \'*\':\n t = 0\n for i in range(len(curr)):\n if curr[i] > 0:\n t = i\n curr[i] -= 1\n break\n for j in range(len(ans) - 1, -1, -1):\n if ans[j] == chr(t + 97):\n ans = ans[0: j] + ans[j + 1: ] \n break\n else:\n curr[ord(s[i]) - 97] += 1\n ans += s[i]\n return ans\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 {\npublic:\n string clearStars(string s) {\n vector<vector<int>> have(26);\n for (int i = 0; i < s.length(); ++i) {\n if (s[i] == \'*\') {\n for (int j = 0; j < 26; ++j) {\n if (!have[j].empty()) {\n have[j].pop_back();\n break;\n }\n }\n } else {\n have[s[i] - \'a\'].push_back(i);\n }\n }\n vector<pair<int, char>> v;\n for (int i = 0; i < 26; ++i) {\n const char c = i + \'a\';\n for (int x : have[i]) {\n v.push_back({x, c});\n }\n }\n sort(v.begin(), v.end());\n string r;\n for (const auto& p : v) {\n r.push_back(p.second);\n }\n return r;\n }\n};\n```
3
0
['Python', 'C++', 'Java', 'Python3']
1
lexicographically-minimum-string-after-removing-stars
C++ | Easy to Understand | using Hashmap🔥✅
c-easy-to-understand-using-hashmap-by-ma-yrof
\n\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n
Mainaaaaak
NORMAL
2024-06-02T04:27:40.570001+00:00
2024-06-02T04:27:40.570025+00:00
150
false
\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n int n = s.length();\n vector<char> arr;\n for (int i = 0;i < n;i++) {\n arr.push_back(s[i]);\n }\n map<char, vector<int>> mp;\n int i = 0;\n while (i < n) {\n if (s[i] != \'*\') {\n mp[s[i]].push_back(i);\n }\n else {\n arr[mp[mp.begin()->first][mp[mp.begin()->first].size()-1]] = \'/\';\n mp[mp.begin()->first].pop_back();\n if (mp[mp.begin()->first].size() == 0) {\n mp.erase(mp.begin()->first);\n }\n }\n i++;\n }\n string ans = "";\n for (auto it : arr) {\n if (int(it) >= 97 and int(it) <= 122) ans += it;\n }\n return ans;\n }\n};\n```
3
0
['C++']
1
lexicographically-minimum-string-after-removing-stars
Java - Max Heap Solution
java-max-heap-solution-by-iamvineettiwar-c2wd
\nclass Solution {\n public String clearStars(String s) {\n PriorityQueue<int[]> pq = new PriorityQueue<int[]>((a, b) -> {\n if (a[0] == b[
iamvineettiwari
NORMAL
2024-06-02T04:09:52.694849+00:00
2024-06-02T04:09:52.694871+00:00
242
false
```\nclass Solution {\n public String clearStars(String s) {\n PriorityQueue<int[]> pq = new PriorityQueue<int[]>((a, b) -> {\n if (a[0] == b[0]) {\n return b[1] - a[1];\n }\n \n return a[0] - b[0];\n });\n char items[] = s.toCharArray();\n \n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == \'*\') {\n int item[] = pq.poll();\n \n items[item[1]] = \'A\';\n \n } else {\n pq.offer(new int[] {s.charAt(i), i});\n }\n }\n \n StringBuilder sb = new StringBuilder("");\n \n for (int i = 0; i < items.length; i++) {\n if (items[i] != \'A\' && items[i] != \'*\') {\n sb.append(items[i]);\n }\n }\n \n return sb.toString();\n }\n}\n```
3
1
['Java']
1
lexicographically-minimum-string-after-removing-stars
Solution Using Priority Queue 🔥✅
solution-using-priority-queue-by-ekansh1-xpi4
Store the pair of {char , index} in the queue on the basis of character such that, character with lowest value and higher index should be given more priority\n2
ekansh1309
NORMAL
2024-06-02T04:06:08.750090+00:00
2024-06-02T04:06:08.750124+00:00
397
false
1. Store the pair of {char , index} in the queue on the basis of character such that, character with lowest value and higher index should be given more priority\n2. we maintained a Cmp to store elements in queue\n3. Vis vector is used to mark the indexes which is removed from the from the string\n4. After that, Just Traverse the string\n5. Use string ans="" to return the result\n5. vis[i] == false and It is not equal to \'*\' just add it in ans\n6. return ans.\nPlease Upvote if You like Thank you :)\nKeep Coding\n\n# Code\n```\nclass Solution {\npublic:\n struct Cmp {\n bool operator()(const pair<char, int>& a, const pair<char, int>& b) const {\n if (a.first != b.first) {\n return a.first > b.first;\n }\n return a.second < b.second;\n }\n};\n\n// void printPriorityQueue(priority_queue<pair<char, int>, vector<pair<char, int>>, Compare> pq) {\n// while (!pq.empty()) {\n// pair<char, int> e = pq.top();\n// pq.pop();\n// cout << "(" << e.first << "," << e.second << ") ";\n// }\n// cout << endl;\n// }\n\n\n string clearStars(string s) {\n priority_queue<pair<char, int>, vector<pair<char, int>>, Cmp> pq;\n int n=s.size();\n vector<int> vis(n,false);\n for (int i = 0; i < n; i++) {\n if(s[i] == \'*\'){\n auto p = pq.top();\n pq.pop();\n char ch = p.first;\n int id = p.second;\n vis[id] = true;\n }\n else{\n pq.push({s[i], i});\n }\n }\n\n string ans="";\n\n for(int i=0;i<n;i++){\n if(!vis[i] && s[i] != \'*\'){\n ans+=s[i];\n }\n }\n\n return ans;\n\n }\n};\n```
3
0
['Heap (Priority Queue)', 'C++']
2
lexicographically-minimum-string-after-removing-stars
Java || 20ms 100% || Intertwined linked lists. Reduce string before processing.
java-20ms-100-intertwined-linked-lists-r-pn1y
Basic algorithm:\n1. Copy the string to an array of characters.\n\n2. Scan string to count \'\\' characters. Reduce string when possible.\n\t1. If no \'\\' in
dudeandcat
NORMAL
2024-06-05T18:27:21.351295+00:00
2024-06-06T06:14:05.815084+00:00
52
false
**Basic algorithm:**\n1. Copy the string to an array of characters.\n\n2. Scan string to count \'\\*\' characters. Reduce string when possible.\n\t1. If no \'\\*\' in the string, then return original string.\n\t2. If string is half \'\\*\'s, then all characters will be deleted, so return empty string.\n\t3. If any \'\\*\' has half of the characters being \'\\*\'s, from beginning of string through that \'\\*\', then all those characters will be deleted, so `start` the processing from just after that \'\\*\'.\n3. Scan characters of copied string previously calculated `start` of processing to end of string.\n\t1. If \'\\*\' char found, then delete the \'\\*\' and the most recently scanned lowest valued letter in the string. Delete characters by setting characters in copied string to zero. Remove the deleted letter from its linked list.\n\t2. Else a letter character, so add that letter to its linked list, and set the head of that letter\'s linked list to the letter in the string.\n\n4. Compress the copied string by removing the zeroes (deleted characters), and return the result as a String.\n\n**Quickly locating rightmost of each letter using intertwined linked lists:**\nEach possible letter \'a\' to \'z\', has its own linked list containing the indexes within the string of that letter, going backward in the string. All 26 of these linked lists are stored intertwined within a single `int[] linkedLists` array of the same length as the string. The heads of these 26 linked lists are stored in the `int[] heads` array.\n\nThe diagram below, for the string "**aabba\\***", shows the relationships of the string, `linkedLists[]`, and `heads[]`, after scanning through the string and reaching the \'\\*\' character. Linked lists have been created for the letters \'a\' and \'b\'.\n\nAlso with the diagram below, for deleting the \'\\*\' along with deleting the lowest-valued previous letter, the \'\\*\' at index 5 is replaced with a zero in the copied string. And `heads[\'a\']` is 4, so the \'a\' at index 4 in the copied string is also replaced with a zero. After deleting the \'a\' at index 4, the linked list for the letter \'a\' is updated by replacing `heads[\'a\']` with `linkedLists[heads[\'a\']]`, which removes the deleted \'a\' from the linked list for the letters \'a\'.\n```\n 0 1 2 3 4 5\n\t\t\t\t___________________________________\nString: \'a\' \'a\' \'b\' \'b\' \'a\' \'*\'\n\n /<\\ /<-----------\\\n / \\ / /<--\\ \\\nlinkedLists[]: -1 0 -1 2 1 ?\n ^ ^\n\t\t\t\t | |\n +-------------------------|---->^\n | +--------------------->^\n\t\t | |\nheads[]: 4 3 -1 -1 -1 -1 ... -1 -1 -1 -1\n ___________________________________\n ... a b c d e f ... w x y z ...\n```\nAfter deleting the \'\\*\' and the \'a\' at index 4::\n```\n 0 1 2 3 4 5\n\t\t\t\t___________________________________\nString: \'a\' \'a\' \'b\' \'b\' 0 0\n\n /<--\\ /<--\\\nlinkedLists[]: -1 0 -1 2 1 ?\n ^ ^\n\t\t\t\t | |\n +------------>^ |\n | +--------------------->^\n\t\t | |\nheads[]: 1 3 -1 -1 -1 -1 ... -1 -1 -1 -1\n ___________________________________\n ... a b c d e f ... w x y z ...\n```\n\n\n\n\n**--- Java code, with better coding practices ---**\n--- Runtime: 21ms to 22ms June 2024 ---\n```\nclass Solution {\n public String clearStars(String s) {\n int n = s.length();\n char[] sc = s.toCharArray();\n\n // Scan the string to get count of asterisks in the \n // string. When encountering an asterisk, if half of \n // the characters from that asterisk back to the \n // beginning of the string are asterisks, then the string \n // from the start through that asterisk have an equal \n // number of letters and asterisks, so that all of the \n // characters up through that asterisk will be deleted, \n // so set the start index for processing the string to \n // the index after that asterisk.\n //\n // If no asterisks in the string, then return the string \n // itself. If exactly half of the characters in the \n // string are asterisks, then the entire string will be \n // deleted so return the empty string.\n int start = 0;\n int asteriskCount = 0;\n for (int i = 0; i < n; i++) {\n if (sc[i] == \'*\') {\n asteriskCount++;\n if (asteriskCount == ((i + 2) >> 1)) \n start = i + 1;\n }\n }\n if (asteriskCount == 0) return s;\n if (start == n) return "";\n \n // Remove \'*\' characters and rightmost lowest characters.\n // Set character values to zero to mark as deleted.\n // The array linkedLists[] contains linked lists, which \n // are indexes into linkedLists[] of the previous \n // occurrence of the same letter, or a -1 if no previous \n // occurrence. The array heads[] is indexed to the start \n // of the letter\'s linked list in the linkedLists[] array. \n // The heads[] array references the rightmost (most recent) \n // occurence of that letter, or -1 is no occurrences of \n // that letter.\n int[] linkedLists = new int[n];\n int[] heads = new int[128];\n for (int i = \'a\'; i <= \'z\'; i++) heads[i] = -1;\n for (int idx = start; idx < n; idx++) {\n int c = sc[idx];\n if (c == \'*\') {\n if (idx >= n) break;\n sc[idx] = 0;\n for (int i = \'a\'; i <= \'z\'; i++) {\n if (heads[i] >= 0) {\n sc[heads[i]] = 0; // Remove a letter from links.\n heads[i] = linkedLists[heads[i]];\n break;\n }\n }\n } else {\n linkedLists[idx] = heads[c]; // Add a letter to links.\n heads[c] = idx;\n }\n }\n \n // Build the result string by removing deleted characters \n // and collapsing the string. Deleted chars were set to \n // zero to mark that they were deleted.\n int outIdx = 0;\n for (int i = start; i < n; i++)\n if (sc[i] != 0)\n sc[outIdx++] = sc[i];\n \n return new String(sc, 0, outIdx);\n }\n}\n```\n**--- Java Code, with faster runtime, but poorer coding practices ---**\n--- Runtime: 20ms to 21ms June 2024 ---\nThe poorer coding practices include using a deprecated form of `getBytes`, converting string characters to `byte` which does not handle unicode, and loop termination that relies on error-free passed values (i.e. the passed string MUST be well formed). But sometimes work projects need speed to meet requirements, especially in real-time device-control programming, so that better programming practices may have to be sacrificed to meet the timing requirements.\n```\nclass Solution {\n public String clearStars(String s) {\n int n = s.length();\n byte[] sc = new byte[n + 1];\n s.getBytes(0, n, sc, 0);\n sc[n] = \'*\'; // Extra \'*\' past end of string so no\n // limit checking needed in FOR loop.\n \n // Scan the string to get count of asterisks in the \n // string. When encountering an asterisk, if half of \n // the characters from that asterisk back to the \n // beginning of the string are asterisks, then the string \n // from the start through that asterisk have an equal \n // number of letters and asterisks, so that all of the \n // characters up through that asterisk will be deleted, \n // so set the start index for processing the string to \n // the index after that asterisk.\n //\n // If no asterisks in the string, then return the string \n // itself. If exactly half of the characters in the \n // string are asterisks, then the entire string will be \n // deleted so return the empty string.\n int start = 0;\n int asteriskCount = 0;\n for (int i = 0; i < n; i++) {\n if (sc[i] == \'*\') {\n asteriskCount++;\n if (asteriskCount == ((i + 2) >> 1)) \n start = i + 1;\n }\n }\n if (asteriskCount == 0) return s;\n if (start == n) return "";\n \n // Remove \'*\' characters and rightmost lowest characters.\n // Set character values to zero to mark as deleted.\n // The array linkedLists[] contains linked lists, which \n // are indexes into linkedLists[] of the previous \n // occurrence of the same letter, or a -1 if no previous \n // occurrence. The array heads[] is indexed to the start \n // of the letter\'s linked list in the linkedLists[] array. \n // The heads[] array references the rightmost (most recent) \n // occurence of that letter, or -1 is no occurrences of \n // that letter.\n int[] linkedLists = new int[n];\n int[] heads = new int[128];\n for (int i = \'a\'; i <= \'z\'; i++) \n heads[i] = -1;\n for (int idx = start; ; idx++) {\n int c = sc[idx];\n if (c == \'*\') {\n if (idx >= n) break;\n sc[idx] = 0;\n for (int i = \'a\'; ; i++) {\n if (heads[i] >= 0) {\n sc[heads[i]] = 0; // Remove a letter from links.\n heads[i] = linkedLists[heads[i]];\n break;\n }\n }\n } else {\n linkedLists[idx] = heads[c]; // Add a letter to links.\n heads[c] = idx;\n }\n }\n \n // Build the result string by removing deleted characters \n // and collapsing the string. Deleted chars were set to \n // zero to mark that they were deleted.\n int outIdx = 0;\n for (int i = start; i < n; i++)\n if (sc[i] != 0)\n sc[outIdx++] = sc[i];\n \n return new String(sc, 0, outIdx);\n }\n}\n```
2
0
['Java']
0
lexicographically-minimum-string-after-removing-stars
Easy Map+SetImplementation💯⭐
easy-mapsetimplementation-by-_rishabh_96-acb0
Clear Stars from String\n\n## Problem Statement\n\nGiven a string s containing lowercase letters and the \'*\' character, remove the character just before each
_Rishabh_96
NORMAL
2024-06-02T09:25:21.315006+00:00
2024-06-02T09:25:21.315042+00:00
71
false
# Clear Stars from String\n\n## Problem Statement\n\nGiven a string `s` containing lowercase letters and the `\'*\'` character, remove the character just before each `\'*\'` along with the `\'*\'` itself and return the final string.\n\n## Intuition\n\nTo solve this problem, we need to keep track of characters that are valid (i.e., not removed due to a `\'*\'` character). A priority queue can help us maintain the order of characters efficiently as we process the string.\n\n## Approach\n\n1. Traverse the string.\n2. Use a priority queue to store non-star characters along with their negative indices (to simulate max-heap behavior with a min-heap).\n3. When encountering a `\'*\'`, pop the top of the priority queue, effectively removing the most recently added non-star character.\n4. Collect the valid indices from the priority queue into a set.\n5. Construct the final string by including only the characters at valid indices.\n\n## Complexity\n\n- **Time complexity:** \\(O(n \\log n)\\) due to the operations involving the priority queue.\n- **Space complexity:** \\(O(n)\\) for storing the valid indices and the priority queue.\n\n## Code\n\n```cpp\nclass Solution {\npublic:\n string clearStars(string s) {\n priority_queue<pair<char, int>, vector<pair<char, int>>, greater<pair<char, int>>> pq; \n\n for (int i = 0; i < s.size(); i++) {\n if (s[i] != \'*\') {\n pq.push({s[i], -i}); \n } else if (s[i] == \'*\') {\n pq.pop();\n }\n }\n\n set<int> validIndices;\n while (!pq.empty()) {\n validIndices.insert(-pq.top().second);\n pq.pop();\n }\n\n string result = "";\n for (int i = 0; i < s.size(); i++) {\n if (validIndices.count(i)) {\n result += s[i];\n }\n }\n\n return result;\n }\n};\n
2
1
['Heap (Priority Queue)', 'Ordered Set', 'C++']
0
lexicographically-minimum-string-after-removing-stars
Time Complexity: O(n)
time-complexity-on-by-twasim-9ke2
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
twasim
NORMAL
2024-06-02T05:21:31.337423+00:00
2024-06-02T05:21:31.337444+00:00
14
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```\nclass Solution {\npublic:\n string clearStars(string s) {\n // set<int> ss;\n priority_queue<int> a[26];\n for (int i=0;i<s.size();i++){\n char x = s[i];\n if (x==\'*\'){\n for (int k=0;k<26;k++){\n if (!a[k].empty() and a[k].top()<i){\n s[a[k].top()]=\'0\';\n a[k].pop();\n break;\n }\n }\n }\n else{\n a[x-\'a\'].push(i);\n }\n }\n string ans="";\n for (auto x:s){\n if (x==\'*\' or x==\'0\')continue;\n ans+=x;\n }\n return ans;\n }\n};\n\n```
2
0
['Heap (Priority Queue)', 'C++']
0
lexicographically-minimum-string-after-removing-stars
Simple Easy Solution using heap||priority Queue||100%beats 🔥🔥
simple-easy-solution-using-heappriority-v39cn
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
bura_uday
NORMAL
2024-06-02T04:42:36.468055+00:00
2024-06-02T04:42:36.468075+00:00
93
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```\nclass Solution {\n public String clearStars(String s) {\n if(!s.contains("*"))\n {\n return s;\n }\n // StringBuffer str=new StringBuffer();\n // for(int i=0;i<s.length();i++)\n // {\n // if(s.charAt(i)!=\'*\')\n // {\n // str.append(s.charAt(i));\n // }\n // else\n // {\n // int j=str.length()-1;\n // int ind=j;\n // char min=str.charAt(j);\n // while(j>=0)\n // {\n // if(str.charAt(j)<min)\n // {\n // min=str.charAt(j);\n // ind=j;\n // }\n // j--;\n // }\n // str.deleteCharAt(ind);\n // }\n // }\n // return str.toString();\n StringBuilder result = new StringBuilder();\n PriorityQueue<Character> pq= new PriorityQueue<>();\n for (char c : s.toCharArray()) {\n if (c != \'*\') {\n result.append(c);\n pq.offer(c); \n } else if (!pq.isEmpty()) {\n char minChar =pq.poll();\n result.deleteCharAt(result.lastIndexOf(String.valueOf(minChar)));\n }\n }\n return result.toString();\n \n }\n}\n```
2
0
['Heap (Priority Queue)', 'Java']
3
lexicographically-minimum-string-after-removing-stars
📌Beats 100% users in python || Easy to Understand ✔|| C++📌 || Java 📌|| JavaScript📌
beats-100-users-in-python-easy-to-unders-jqaz
Intuition\n Describe your first thoughts on how to solve this problem. \nVery clear intuition is do what it asks for. You will get accepted.\n\n# Approach\n Des
aryankshl
NORMAL
2024-06-02T04:36:32.805176+00:00
2024-06-02T04:36:32.805202+00:00
91
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nVery clear intuition is do what it asks for. You will get accepted.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirstly you need to keep track of the smallest character with largest index till the current \'star\'. This can be easily done using map data structure, create a map of char and vector in which put indexes of the current character at the back so the closest one is the last element of the vector of that char. Because we are using map data structure so it automatically sorts the characters in it. So just by accessing the first characters last index does the work. Now mark the indexes of \'star\' and the characters index.\nNow iterate through the string and create your answer by not taking the indexes you marked.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code in C++, Java, Python and JavaSript\n```C++ []\nclass Solution {\npublic:\n string clearStars(string s) {\n map<char,vector<int>> mp;\n int n= s.size();\n vector<int> v(n,0);\n for(int i =0 ;i <s.size(); i++){\n if(s[i]!=\'*\'){\n mp[s[i]].push_back(i);\n }\n else{\n v[i] = 1;\n for(auto &x : mp){\n int m = x.second.size();\n v[x.second[m-1]] = 1;\n x.second.pop_back();\n if(x.second.size()==0) mp.erase(x.first);\n break;\n }\n }\n }\n string ans ="";\n for(int i = 0; i<n; i++){\n if(v[i]!=1) ans+=s[i];\n }\n return ans;\n }\n};\n```\n```Java []\nclass Solution {\n public String clearStars(String s) {\n TreeMap<Character, List<Integer>> mp = new TreeMap<>();\n int n = s.length();\n int[] v = new int[n];\n \n for (int i = 0; i < n; i++) {\n if (s.charAt(i) != \'*\') {\n mp.computeIfAbsent(s.charAt(i), k -> new ArrayList<>()).add(i);\n } else {\n v[i] = 1;\n for (Map.Entry<Character, List<Integer>> entry : mp.entrySet()) {\n List<Integer> indices = entry.getValue();\n int m = indices.size();\n v[indices.get(m - 1)] = 1;\n indices.remove(m - 1);\n if (indices.isEmpty()) {\n mp.remove(entry.getKey());\n }\n break;\n }\n }\n }\n \n StringBuilder ans = new StringBuilder();\n for (int i = 0; i < n; i++) {\n if (v[i] != 1) {\n ans.append(s.charAt(i));\n }\n }\n return ans.toString();\n }\n}\n```\n```python []\nclass Solution(object):\n def clearStars(self, s):\n # Using defaultdict to store the indices of each character\n mp = defaultdict(list)\n n = len(s)\n v = [0] * n\n\n for i in range(n):\n if s[i] != \'*\':\n mp[s[i]].append(i)\n else:\n v[i] = 1\n # Sort the dictionary by key\n sorted_mp = OrderedDict(sorted(mp.items()))\n for key in list(sorted_mp.keys()):\n idx_list = sorted_mp[key]\n v[idx_list[-1]] = 1\n idx_list.pop()\n if not idx_list:\n del mp[key]\n break\n\n ans = ""\n for i in range(n):\n if v[i] != 1:\n ans += s[i]\n\n return ans\n \n```\n```JavaScript []\n/**\n * @param {string} s\n * @return {string}\n */\nvar clearStars = function(s) {\n const mp = new Map();\n const n = s.length;\n const v = new Array(n).fill(0);\n\n for (let i = 0; i < n; i++) {\n if (s[i] !== \'*\') {\n if (!mp.has(s[i])) {\n mp.set(s[i], []);\n }\n mp.get(s[i]).push(i);\n } else {\n v[i] = 1;\n const sortedEntries = Array.from(mp.entries()).sort((a, b) => a[0].localeCompare(b[0]));\n for (let [key, indices] of sortedEntries) {\n const m = indices.length;\n v[indices[m - 1]] = 1;\n indices.pop();\n if (indices.length === 0) {\n mp.delete(key);\n }\n break;\n }\n }\n }\n\n let ans = "";\n for (let i = 0; i < n; i++) {\n if (v[i] !== 1) {\n ans += s[i];\n }\n }\n return ans;\n};\n```\n![upvoting image.jpeg](https://assets.leetcode.com/users/images/d9d1ccc8-1b2e-404e-963c-2707067544d1_1717302529.8161004.jpeg)\n
2
0
['Python', 'C++', 'Java', 'Python3', 'JavaScript']
1
lexicographically-minimum-string-after-removing-stars
O(N) using stack
on-using-stack-by-surajthapliyal-880x
Maintain an array of stacks where each element will contain a stack of indices of its occurence.\nRemove the last index of the smallest character whenever encou
surajthapliyal
NORMAL
2024-06-02T04:30:20.271597+00:00
2024-06-02T04:41:14.761519+00:00
556
false
Maintain an array of stacks where each element will contain a stack of indices of its occurence.\nRemove the last index of the smallest character whenever encounter a \'*\' .\nWe are removing last index because we want to make lexi. smallest string so we want to keep smallest characters in front of the string.\n\n```\nclass Solution {\n public String clearStars(String str) {\n char a[] = str.toCharArray();\n Stack<Integer>[] s = new Stack[26];\n for(int i=0;i<26;i++) s[i] = new Stack<>();\n for(int i=0;i<a.length;i++) {\n if(a[i] == \'*\') {\n for(int j=0;j<26;j++) {\n if(!s[j].isEmpty()) {\n int index = s[j].pop();\n a[index] = \'*\';\n break;\n }\n }\n }else{\n s[a[i]-\'a\'].push(i);\n }\n }\n StringBuilder sb = new StringBuilder();\n for(char ch : a) if(ch !=\'*\') sb.append(ch);\n return sb.toString();\n }\n}\n```
2
0
[]
0
lexicographically-minimum-string-after-removing-stars
Python | O(n^2) passed
python-on2-passed-by-xxxxtj-jqf5
\n\n# Code\n\nclass Solution:\n def clearStars(self, s: str) -> str:\n stack = []\n\n for char in s:\n if char != "*":\n
xxxxtj
NORMAL
2024-06-02T04:13:51.796058+00:00
2024-06-02T04:13:51.796091+00:00
102
false
\n\n# Code\n```\nclass Solution:\n def clearStars(self, s: str) -> str:\n stack = []\n\n for char in s:\n if char != "*":\n stack.append(ord(char))\n else:\n index = stack[::-1].index(min(stack))\n stack.pop(len(stack) - 1 - index)\n res = ""\n\n for c in stack:\n res += chr(c)\n return res\n\n```
2
0
['Python3']
2
lexicographically-minimum-string-after-removing-stars
[Python] - Storing indices in a heap
python-storing-indices-in-a-heap-by-srin-yoci
Intuition\n Describe your first thoughts on how to solve this problem. \nWe need to remove the most recent small character, so that lexicographically it will be
Srinu2568
NORMAL
2024-06-02T04:12:40.426160+00:00
2024-06-02T04:18:33.144641+00:00
179
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to remove the most recent small character, so that lexicographically it will be small. If we remove the first small character from the beginning the string becomes lexicographically big.\nEx:\ns = \'aaba*\'\nHere the small character to the left of \'*\' is \'a\'. We have three a\'s at the indexes [0, 1, 3].\nIf we remove, \nat index - 0: \'aba\'\nat index - 1: \'aba\'\nat index - 3: \'aab\'\nSo, if we remove the character \'a\' at recent index, It would become lexicographically small.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse heap/priority queue to store the characters and their indices.\n```\nheapq.heappush(heap, (s[i], -i))\n``` \nStore the negative index, because heap gives us the smallest element first. Later use that index to mark the element of ans array to \'0\'.\n```python\ns = \'\'\nfor c in ans:\n if c and c != \'*\': s += c\n```\nFinally to get the output string, join every character in the array except for the \'*\' and 0 values.\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```python\nclass Solution:\n def clearStars(self, s: str) -> str:\n heap, ans = [], []\n i, n = 0, len(s)\n while i < n:\n if s[i] == \'*\':\n el, index = heapq.heappop(heap)\n ans[-index] = 0\n else:\n heapq.heappush(heap, (s[i], -i))\n ans.append(s[i])\n i += 1\n s = \'\'\n for c in ans:\n if c and c != \'*\': s += c\n return s\n```
2
0
['Array', 'String', 'Heap (Priority Queue)', 'Python3']
2
lexicographically-minimum-string-after-removing-stars
Using set
using-set-by-aayu_t-6b33
\n\n# Code\n\nclass Solution {\npublic:\n string clearStars(string s) \n {\n int n = s.length(); \n string r = "";\n set<pair<char,
aayu_t
NORMAL
2024-06-02T04:11:08.096124+00:00
2024-06-02T04:11:08.096151+00:00
19
false
\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) \n {\n int n = s.length(); \n string r = "";\n set<pair<char, int>> st;\n for(int j = 0; j < n; j++)\n {\n if(s[j] == \'*\')\n {\n pair<char, int> p = *st.begin();\n int index = p.second;\n s[-index] = \'*\';\n st.erase(st.begin());\n }\n else st.insert({s[j], -j});\n }\n for(int i = 0; i < n; i++)\n {\n if(s[i] != \'*\') r += s[i];\n }\n return r;\n }\n};\n```
2
0
['Ordered Set', 'C++']
0
lexicographically-minimum-string-after-removing-stars
Delete Rightmost element
delete-rightmost-element-by-harshitcode-tja4
Intuition\n Describe your first thoughts on how to solve this problem. \nMy intuition was we will delete the smallest then it is always good to delete the last
Harshitcode
NORMAL
2024-06-02T04:09:34.598921+00:00
2024-06-02T04:09:34.598956+00:00
105
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy intuition was we will delete the smallest then it is always good to delete the last index smallest so thats what i did i simply used the set to get the index i should skip.\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 {\npublic:\n string clearStars(string s) {\n vector<vector<int>>ok(26);\n set<int>st;\n for(int i = 0;i<s.size();i++){\n if(s[i]==\'*\'){\n for(int j=0;j<26;j++){\n if(ok[j].size()>0){\n st.insert(ok[j].back());\n ok[j].pop_back();\n break;\n }\n }\n }else{\n ok[s[i]-\'a\'].push_back(i);\n }\n }\n string ans = "";\n for(int i = 0;i<s.size();i++){\n if(st.count(i) == false && s[i]!=\'*\'){\n ans+=s[i];\n }\n }\n return ans;\n }\n};\n```
2
1
['C++']
1
lexicographically-minimum-string-after-removing-stars
✅ Java Solution
java-solution-by-harsh__005-198u
CODE\nJava []\npublic String clearStars(String s) {\n\tchar[] arr = s.toCharArray();\n\n\tPriorityQueue<Integer> pq = new PriorityQueue<>((i,j)->{\n\t\tif(arr[i
Harsh__005
NORMAL
2024-06-02T04:08:37.092984+00:00
2024-06-02T04:08:37.093022+00:00
266
false
## **CODE**\n```Java []\npublic String clearStars(String s) {\n\tchar[] arr = s.toCharArray();\n\n\tPriorityQueue<Integer> pq = new PriorityQueue<>((i,j)->{\n\t\tif(arr[i] == arr[j]) return j-i;\n\t\treturn arr[i]-arr[j];\n\t});\n\n\tfor(int i=0; i<arr.length; i++) {\n\t\tif(arr[i] == \'*\') {\n\t\t\tint top = pq.remove();\n\t\t\tarr[top] = \'-\';\n\t\t} else {\n\t\t\tpq.add(i);\n\t\t}\n\t}\n\n\tString res = "";\n\tfor(char ch : arr) {\n\t\tif(ch != \'*\' && ch != \'-\') {\n\t\t\tres += ch;\n\t\t} \n\t}\n\n\treturn res;\n}\n```
2
0
['Java']
2
lexicographically-minimum-string-after-removing-stars
Beats 💯 | Easy solution | ✅ nLogn | Heap
beats-easy-solution-nlogn-heap-by-bhanub-gdfy
Intuition\n Describe your first thoughts on how to solve this problem. \nIn this problem we just need to pay attention on two points \n 1. smallest character oc
Bhanubediya
NORMAL
2024-06-02T04:08:36.651793+00:00
2024-06-02T04:25:05.835026+00:00
46
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn this problem we just need to pay attention on two points \n 1. smallest character occuring before *****.\n 2. smallest the removal of character should be of highest index if theres a repeatition of same characters before a *****.\n \nSince we need to remove characters based from string S based on the above observations, **PrioirityQueue(Min Heap)** comes in the picture cause \n1. It can sort the characters in an ascending order.\n2. It can also sort the characters based on their indices if the characters are repeated. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n Lets discuss the approach.\n we can use a class Pair or array of int[] to store each characters and their indices in priorityQueue.\n 1. Traverse the loop and check if the current character is a ***** then don\'t push in the PQ, just remove the top character from the PQ if the PQ is not empty.\n 2. To Store the characters left in the PQ we\'ll use **ArrayList** and then jus sort it based on their indices to get the correct ordering of the characters.\n 3. Traverse the list and store the characters in the StringBuilder and return it.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n**nlogn**\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nconstant O(n^2)\n# Code\n```\n class Pair{\n char c;\n int ind;\n public Pair(char c,int ind){\n this.c=c;\n this.ind=ind;\n }\n }\nclass Solution {\n public String clearStars(String s) {\n PriorityQueue<Pair>pq=new PriorityQueue<>((a,b)->{\n if(a.c!=b.c){\n return a.c-b.c;\n }\n else{\n return b.ind-a.ind;\n }\n });\n int i=0;\n for(char ch:s.toCharArray()){\n if(ch==\'*\'){\n if(!pq.isEmpty()){\n pq.poll();\n }\n }else{\n pq.offer(new Pair(ch,i));\n }\n i++;\n }\n ArrayList<Pair>list=new ArrayList<>();\n while(!pq.isEmpty()){\n list.add(pq.poll());\n }\n Collections.sort(list,(a,b)->a.ind-b.ind);\n StringBuilder sb=new StringBuilder();\n for(Pair num:list){\n sb.append(num.c);\n }\n return sb.toString();\n }\n}\n```
2
0
['Sorting', 'Heap (Priority Queue)', 'Java']
0
lexicographically-minimum-string-after-removing-stars
Simple C++ Solution | minheap and map of stack
simple-c-solution-minheap-and-map-of-sta-cfhe
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
Abhishek_499
NORMAL
2024-06-02T04:03:51.444293+00:00
2024-06-02T04:30:39.959051+00:00
59
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)$$ -->\nPlease upvote if the solution helps \n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n \n priority_queue<char, vector<char>, greater<char>> pq;\n \n unordered_map<char, stack<int>> mp;\n \n unordered_set<int> indexes;\n \n for(int i=0;i<s.size();i++){\n if(s[i]!=\'*\'){\n\n mp[s[i]].push(i);\n pq.push(s[i]);\n }else{\n \n auto val=pq.top();\n pq.pop();\n int index=mp[val].top();\n mp[val].pop();\n \n \n indexes.insert(i);\n indexes.insert(index);\n \n }\n }\n \n string res="";\n \n for(int i=0;i<s.size();i++){\n if(indexes.find(i)!=indexes.end())\n continue;\n \n res+=s[i];\n }\n \n return res;\n \n }\n};\n```
2
0
['C++']
1
lexicographically-minimum-string-after-removing-stars
[C++] Heap NlogN
c-heap-nlogn-by-hansman-ywho
\n\n\n\n\nclass Solution {\npublic:\n struct CompareStruct {\n bool operator() (pair a, pair b) {\n if (a.first > b.first) {\n
hansman
NORMAL
2024-06-02T04:02:14.814942+00:00
2024-06-02T04:02:14.814972+00:00
83
false
\n\n\n\n\nclass Solution {\npublic:\n struct CompareStruct {\n bool operator() (pair<int, int> a, pair<int, int> b) {\n if (a.first > b.first) {\n return true;\n } else if (a.first == b.first) {\n return a.second < b.second;\n }\n return false;\n }\n };\n \n string clearStars(string s) {\n unordered_set<int> indexesToDelete;\n priority_queue<pair<int, int>, vector<pair<int, int>>, CompareStruct> heap;\n \n \n for (int i = 0; i < s.size(); i++) {\n if (s[i] != \'*\') {\n heap.push({s[i], i});\n } else {\n indexesToDelete.insert(heap.top().second);\n heap.pop();\n }\n }\n \n string ans = "";\n for (int i = 0; i < s.size(); i++) {\n if (indexesToDelete.count(i)) {\n continue;\n } else if (s[i] != \'*\') {\n ans.push_back(s[i]);\n }\n }\n \n return ans;\n }\n};\n```
2
1
['C++']
1
lexicographically-minimum-string-after-removing-stars
Heap and hashmap for storing indexes
heap-and-hashmap-for-storing-indexes-by-4tgqf
null
saitama1v1
NORMAL
2024-12-12T19:19:15.297752+00:00
2024-12-12T19:19:15.297752+00:00
21
false
# Complexity\n- Time complexity:\nO(n * logk), where k is number of distinct characters\n- Space complexity:\nO(n)\n# Code\n```python3 []\nclass Solution:\n def clearStars(self, s: str) -> str:\n smallest_letters, n = [], len(s)\n indexes = defaultdict(list)\n res = []\n for i in range(n):\n if s[i] == \'*\':\n x = heappop(smallest_letters)\n last = indexes[x].pop()\n res[last] = \'\'\n if len(indexes[x]) > 0:\n heappush(smallest_letters, x)\n res.append(\'\')\n else:\n if len(indexes[s[i]]) == 0:\n heappush(smallest_letters, s[i])\n indexes[s[i]].append(i)\n res.append(s[i])\n \n return \'\'.join(res)\n\n\n\n\n\n \n```
1
0
['Hash Table', 'Heap (Priority Queue)', 'Python3']
0
lexicographically-minimum-string-after-removing-stars
✅C++ Solution || No Heap || No Map
c-solution-no-heap-no-map-by-14mayank14-bzy7
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
14mayank14
NORMAL
2024-09-01T14:23:34.451645+00:00
2024-09-01T14:23:34.451672+00:00
8
false
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution{\npublic:\n string clearStars(string s){\n int len = s.length();\n vector<bool> include(len, true);\n vector<vector<int>> indexes(26);\n\n for(int i = 0; i < len; ++i){\n if(s[i] == \'*\'){\n include[i] = false;\n \n int j = 0;\n while(j<26 && indexes[j].size()==0)\n ++j;\n \n if(j==26)\n continue;\n \n include[indexes[j].back()] = false;\n indexes[j].pop_back();\n }\n else\n indexes[s[i]-\'a\'].push_back(i);\n }\n\n string res = "";\n for(int i = 0; i < len; ++i){\n if(include[i])\n res += s[i];\n }\n\n return res;\n }\n};\n```
1
0
['C++']
0
lexicographically-minimum-string-after-removing-stars
Easy C++ solution.
easy-c-solution-by-coder_sd-6qvj
Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n\nclass Solution {\npublic:\n string clearStars(string s) {\n priority_queu
coder_sd
NORMAL
2024-06-09T12:33:59.095996+00:00
2024-06-09T12:33:59.096024+00:00
41
false
# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n priority_queue<char, vector<char>, greater<char>> pq;\n unordered_map<char, stack<int>> stk;\n for(int i=0;i<s.length();i++){\n if(s[i]==\'*\'){\n if(!pq.empty()){\n char tp=pq.top();\n stk[tp].pop();\n if(stk[tp].size()==0){\n stk.erase(tp);\n pq.pop();\n }\n }\n }\n else{\n if(stk.find(s[i])==stk.end()){\n pq.push(s[i]);\n }\n stk[s[i]].push(i);\n }\n }\n vector<pair<int,char>> v;\n for(auto it:stk){\n while(!it.second.empty()){\n v.push_back({it.second.top() , it.first});\n it.second.pop();\n }\n }\n sort(v.begin(), v.end());\n string res="";\n for(auto it:v){\n string s1(1, it.second);\n res+=s1;\n }\n return res;\n }\n};\n```
1
0
['Stack', 'Sorting', 'Heap (Priority Queue)', 'C++']
0
lexicographically-minimum-string-after-removing-stars
Modified Priority_Queue Approach with very less lines...😁😁😁😁😁
modified-priority_queue-approach-with-ve-c6dw
Code\n\nclass Solution {\npublic:\n struct comp {\n bool operator()(const pair<char, int>& a, const pair<char, int>& b) const {\n if (a.fir
KanishYathraRaj
NORMAL
2024-06-07T10:24:43.520194+00:00
2024-06-07T10:24:43.520218+00:00
6
false
# Code\n```\nclass Solution {\npublic:\n struct comp {\n bool operator()(const pair<char, int>& a, const pair<char, int>& b) const {\n if (a.first == b.first) return a.second < b.second; \n return a.first > b.first; \n }\n };\n string clearStars(string s) {\n priority_queue<pair<char, int>, vector<pair<char, int>>, comp> pq;\n\n for (int i = 0; i < s.size(); ++i) {\n if (s[i] != \'*\') pq.push({s[i], i});\n else pq.pop();\n }\n vector<int> v;\n while (!pq.empty()) {\n v.push_back(pq.top().second);\n pq.pop();\n }\n sort(v.begin(), v.end());\n string res;\n for (int i : v) res += s[i];\n \n return res;\n }\n};\n\n```
1
0
['C++']
0
lexicographically-minimum-string-after-removing-stars
🔥Very Easy to understand and intuitive 🔥approach.Beginner friendly
very-easy-to-understand-and-intuitive-ap-aqo0
\n\n# Complexity\n- Time complexity:\n O(nlogn) \n\n- Space complexity:\n O(n) \n\n# Code\n\nclass Solution {\npublic:\n string clearStars(string s) {\n
Saksham_Gulati
NORMAL
2024-06-05T17:51:12.741668+00:00
2024-06-05T17:51:12.741690+00:00
16
false
\n\n# Complexity\n- Time complexity:\n $$O(nlogn)$$ \n\n- Space complexity:\n $$O(n)$$ \n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n set<pair<char,int>>st;\n int c=0;\n for(auto i:s)\n {\n if(i==\'*\')\n {\n if(st.size())\n {\n st.erase(st.begin());\n }\n }\n else\n {\n st.insert({i,-c});\n }\n c++;\n }\n vector<pair<int,char>>v;\n for(auto i:st)\n {\n v.push_back({-i.second,i.first});\n }\n sort(v.begin(),v.end());\n string ans;\n for(auto i:v)ans.push_back(i.second);\n return ans;\n \n }\n};\n```
1
0
['Ordered Set', 'C++']
0
lexicographically-minimum-string-after-removing-stars
🔥O(n) || ✅ Min heap || Without Custom Comparator ✅ || C++
on-min-heap-without-custom-comparator-c-ngx1f
Approach\n- Insert char and -1 * index in priority queue.\n- if 2 char are same, we will delete char present at max index means every time pq.top() will give me
Its_AK7
NORMAL
2024-06-04T19:56:14.129885+00:00
2024-06-04T19:56:14.129914+00:00
58
false
# Approach\n- Insert **char** and **-1 * index** in priority queue.\n- if 2 char are same, we will delete char present at max index means every time pq.top() will give me my required element and its index.\n- We simply mark pq.top() element as **\'*\'**.\n- In ans return all the elements of string s which are not **\'***\'.\n\n# Complexity\n- Time complexity: O(n)\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n string clearStars(string s) {\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;\n for(int i=0;i<s.size();i++){\n if(s[i]==\'*\'){\n s[-pq.top().second]=\'*\';\n pq.pop();\n }\n else pq.push({s[i]-\'a\',-i});\n }\n string ans="";\n for(auto& c:s) if(c!=\'*\') ans+=c;\n return ans;\n }\n};\n```\n\nDo upvote if you found this useful.\n\n
1
0
['String', 'Greedy', 'Heap (Priority Queue)', 'C++']
0
lexicographically-minimum-string-after-removing-stars
Java | Easy | Priority Queue
java-easy-priority-queue-by-priyadarshi_-qc2k
Intuiton:\nIf you look closely, this problem is a problem of priority queue and how well you handle a string. The queue is made on two criteria:\n it takes in a
Priyadarshi_codes
NORMAL
2024-06-04T11:58:45.923820+00:00
2024-06-04T11:58:45.923861+00:00
72
false
**Intuiton**:\nIf you look closely, this problem is a problem of priority queue and how well you handle a string. The queue is made on two criteria:\n* it takes in a variable *pri* with character and integer as attributes. First it sorts all the characters it takes in pri in lexicographical order. This we achieve by` Character.compare(a.let, b.let)`\n* If characters are same, I need the nearest of them (nearest to the * ) to make the end string lexicographically smallest. Since I will be traversing the string left to right, I will be storing the indices of where the characters have occured in the other attribute of class pri. This I have to sort in decreasing order. When indices stored as int are arranged in descending order, the closest to the present iterator would get prioritized.\n*Another challenge of this problem is to know that any mutation on string or string-builder while we are still checking where characters have appeared would impact the mutation itself*. In other words, you have to do the two task of collecting indices where characters will be deleted AND the task of deleting such characters separetely. Otherwise indices would go hay-wire.\n\n**Approach**:\n1. Use a priority queue to do the sorting as required.\n2. Wherever you get a * , retrieve the head of the priority queue and collect the integer index it represent in a list or set\n3. Poll the head as we are done with it.\n4. To build the string, travel through the string in a different loop, and exclude the * and whenever the index appears in the set.\n5. Return the string buildre as string\n\n\n```\n\nclass pri{\n\tint pos;char let;\n\tpri(int pos,char let){\n\t\tthis.pos=pos;\n\t\tthis.let=let;\n\t}\n}\n\n\nclass Solution {\n public String clearStars(String s) {\n int pos=-1;char cur;\n\t\t \tStringBuilder sb=new StringBuilder();\n\t\t Set<Integer> lt=new HashSet<>();\n\t PriorityQueue<pri> q=new PriorityQueue<>(new Comparator<pri>() {\n\t \tpublic int compare(pri a,pri b) {\n\t \t\tif(Character.compare(a.let, b.let)!=0)\n\t \t\t\treturn Character.compare(a.let, b.let);\n\t \t\treturn Integer.compare(b.pos,a.pos);\n\t \t}\n\t });\n\t \n\t for(int i=0;i<s.length();i++) { \n\t \tif(s.charAt(i)!=\'*\') { \n\t \t\tq.add(new pri(i,s.charAt(i)));\n\t \t\tpos=q.peek().pos;\n\t \t\t}\n\t \telse {\n\t \t\tlt.add(pos);\n\t \t\tq.poll();\n\t \t\tif(!q.isEmpty()) pos=q.peek().pos;\n\t \t}\n\t }\n\t \n\t for(int i=0;i<s.length();i++) {\n\t \tif(s.charAt(i)!=\'*\'&&!lt.contains(i))\n\t \t\tsb.append(s.charAt(i));\n\t }\n\t \n\t return new String(sb);\n }\n}\n\n```\n\n**Time Complexity**:\nO(N) We ran through the string twice\n\n**Space Complexity**:\nO(N) for the set
1
0
['Java']
0
lexicographically-minimum-string-after-removing-stars
Easy-Peasy Solution using Set
easy-peasy-solution-using-set-by-anshuba-gy3x
Intuition\n Describe your first thoughts on how to solve this problem. \njust maintain a sorted set and which is internally sorted based on the index in negativ
anshubaloria123
NORMAL
2024-06-04T09:52:50.265978+00:00
2024-06-04T09:52:50.265996+00:00
282
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\njust maintain a sorted set and which is internally sorted based on the index in negative order to get the nearest smallest char from left side \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)$$ -->o(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->o(n)\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n set<pair<char,int>> st;\n string res;\n for(int i=0;i<s.length();i++)\n {\n if(s[i]==\'*\')\n {\n pair<char,int>p =*st.begin();\n int del=-(p.second);\n s[del-1]=\'*\';\n st.erase(st.begin());\n }\n else\n st.insert({s[i],(i+1)*-1});\n }\n cout<<s<<endl;\n for(auto v:st)\n cout<<v.first<<" "<<v.second<<endl;\n for(int i=0;i<s.length();i++)\n {\n if(s[i]!=\'*\')res+=s[i];\n }\n return res;\n }\n};\n```
1
0
['Ordered Set', 'C++']
1
lexicographically-minimum-string-after-removing-stars
Having Memory Limit Exceeded ! Can anyone help?
having-memory-limit-exceeded-can-anyone-64jez
Can somebody explain why my 2nd Approach (Used unordered_map>)didn\'t work but 1st Approach (vector>) worked.\n+ I agree :\nThat the 1st approach is a bit optim
ace_pie06
NORMAL
2024-06-03T11:08:03.876784+00:00
2024-06-03T11:08:03.876816+00:00
11
false
Can somebody explain why my 2nd Approach (Used unordered_map<int,vector<int>>)didn\'t work but 1st Approach (vector<vector<int>>) worked.\n+ I agree :\nThat the 1st approach is a bit optimised but that should effec T.C. right?\nBut my 2nd approach is having Memory Limit exceeded! How ??\n\n## Approach 1\n### (vector<vector<int>>mp(26,vector<int>())) [Accepted]\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n int n=s.size();\n vector<vector<int>>mp(26,vector<int>());\n for(int i=0;i<n;i++)\n {\n if(s[i]!=\'*\')\n {\n mp[s[i]-\'a\'].push_back(i);\n }\n else if(s[i]==\'*\')\n {\n for(int j=0;j<26;j++)\n {\n if(mp[j].size()>0)\n {\n int idx=mp[j][mp[j].size()-1];\n s[idx]=\'*\';\n mp[j].pop_back();\n break;\n }\n }\n }\n }\n string ans="";\n for(int i=0;i<n;i++)\n {\n if(s[i]!=\'*\')\n {\n ans+=s[i];\n }\n }\n return ans;\n }\n};\n```\n## Approach 2 \n### (unordered_map<char,vector<int>>mp)[Memory Limit Exceeded]\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n int n=s.size();\n unordered_map<char,vector<int>>mp;\n for(int i=0;i<n;i++)\n {\n if(s[i]!=\'*\')\n {\n mp[s[i]].push_back(i);\n }\n else\n {\n char smallest=\'z\';\n for(auto it:mp)\n {\n if(it.first<smallest && it.second.size()>0)\n {\n smallest=it.first;\n }\n }\n int idx=mp[smallest][mp[smallest].size()-1];\n s[idx]=\'*\';\n mp[smallest].pop_back();\n }\n }\n string ans="";\n for(int i=0;i<n;i++)\n {\n if(s[i]!=\'*\')\n {\n ans+=s[i];\n }\n }\n return ans;\n }\n};\n```\nPlease help!\nThank You.
1
0
['C']
0
lexicographically-minimum-string-after-removing-stars
|| shark tank approach || cpp || priority_queue ||
shark-tank-approach-cpp-priority_queue-b-odmw
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
Cookie_byte
NORMAL
2024-06-03T09:33:28.113811+00:00
2024-06-03T09:33:28.113827+00:00
4
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#include <queue>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nclass Solution {\npublic:\n string clearStars(string s) {\n // Define the priority queue correctly\n priority_queue<char, vector<char>, greater<char>> pq;\n \n for (int i = 0; i < s.size(); ++i) {\n if (s[i] == \'*\') {\n // Remove the current \'*\'\n s.erase(i, 1);\n // Decrease index to check the new character at the same position\n --i;\n\n // Find the closest previous character that is not \'*\'\n int j = i;\n while (j >= 0 && (s[j] == \'*\' || s[j] != pq.top())) {\n --j;\n }\n\n // Remove the character if found\n if (j >= 0 && s[j] == pq.top()) {\n s.erase(j, 1);\n --i; // Adjust the index again after erasing\n }\n\n if (!pq.empty()) {\n pq.pop();\n }\n } else {\n pq.push(s[i]);\n }\n }\n\n return s;\n }\n};\n\n```
1
0
['C++']
0
lexicographically-minimum-string-after-removing-stars
Easy C++ || Priority Queue(Min Heap) || O(nlogn) 🔥🚀💯
easy-c-priority-queuemin-heap-onlogn-by-7qoin
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
nikhil73995
NORMAL
2024-06-03T02:52:45.425214+00:00
2024-06-03T02:52:45.425240+00:00
7
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```\nclass Solution {\npublic:\n string clearStars(string s) {\n priority_queue<pair<char, int>, vector<pair<char, int>>, greater<pair<char, int>>>heap; \n for (int i = 0; i < s.size(); i++) {\n if (s[i] != \'*\') {\n heap.push({s[i], -i}); \n } else if (s[i] == \'*\') {\n heap.pop();\n }\n }\n \n set<int> st;\n while (!heap.empty()) {\n st.insert(-heap.top().second);\n heap.pop();\n }\n \n string result = "";\n for (int i = 0; i < s.size(); i++) {\n if (st.count(i)) {\n result += s[i];\n }\n }\n \n return result;\n }\n};\n```
1
0
['Heap (Priority Queue)', 'Ordered Set', 'C++']
0
lexicographically-minimum-string-after-removing-stars
C++, O(n), scan with a map
c-on-scan-with-a-map-by-fzh-anhx
Intuition\nJust delete the rightmost occurrence of the min-char seen so far, when scanning the string from left to right.\n\n# Approach\nuse a map to maintain t
fzh
NORMAL
2024-06-03T01:58:33.556506+00:00
2024-06-03T01:58:33.556527+00:00
0
false
# Intuition\nJust delete the rightmost occurrence of the min-char seen so far, when scanning the string from left to right.\n\n# Approach\nuse a map to maintain the min char seen so far, with\nthe positions of its occurrences. \nSo that map is map<char, vector<int>>\n\n# Complexity\n- Time complexity:\nO(n * log 26) == O(n)\n\n- Space complexity:\nO(n + 26) == O(n)\n\n# Code\n```\n// Idea: always greedily delete the rightmost occurrence of \n// the min char seen so far.\n// use a map to maintain the min char seen so far, with\n// the positions of its occurrences.\nclass Solution {\npublic:\n string clearStars(string s) {\n // maps a unique char to the positions of its occurrences.\n map<char, vector<int>> m; \n // count of non-star chars seen so far.\n // this variable can be deleted, as it\'s only for asserts.\n int cnt = 0; \n for (int i = 0; i < s.size(); ++i) {\n const char c = s[i];\n if (c == \'*\') {\n // assert(cnt > 0);\n // assert(!m.empty());\n s[i] = \'-\';\n auto iter = m.begin();\n // assert(!iter->second.empty());\n int pos = iter->second.back();\n // delete the char\n --cnt;\n s[pos] = \'-\';\n iter->second.pop_back();\n if (iter->second.empty()) {\n m.erase(iter->first);\n }\n } else {\n // maintain the cnt and the map\n ++cnt;\n m[c].push_back(i); // record its pos\n }\n }\n string res;\n for (char c : s) {\n if (c != \'-\') {\n res += c;\n }\n }\n return res;\n }\n};\n```
1
0
['C++']
0
lexicographically-minimum-string-after-removing-stars
[Python] dict of list of indexes (beats 100%) O(N)
python-dict-of-list-of-indexes-beats-100-3z5p
\n"""\nSupport here dict of indexes, to fast replace smallest character\n\nTC: O(N)\nSC: O(N)\n"""\nclass Solution:\n def clearStars(self, s: str) -> str:\n
pbelskiy
NORMAL
2024-06-02T22:00:31.782934+00:00
2024-06-02T22:00:31.782957+00:00
8
false
```\n"""\nSupport here dict of indexes, to fast replace smallest character\n\nTC: O(N)\nSC: O(N)\n"""\nclass Solution:\n def clearStars(self, s: str) -> str:\n a = []\n d = defaultdict(list)\n\n for ch in s:\n if ch != \'*\':\n d[ch].append(len(a))\n a.append(ch)\n continue\n\n m = min(d)\n\n i = d[m].pop()\n a[i] = \'~\'\n if len(d[m]) == 0:\n del d[m]\n\n return \'\'.join(filter(lambda ch: ch != \'~\', a))\n```
1
0
['Python']
0
lexicographically-minimum-string-after-removing-stars
Simple | Clean Code | Beats 99% | 1ms | C++ | Greedy | Sorting | Brute Force
simple-clean-code-beats-99-1ms-c-greedy-oxin1
\n Describe your first thoughts on how to solve this problem. \n# Approach and Intuition\n Describe your approach to solving the problem. \nWrite Brute Force Fo
Don007
NORMAL
2024-06-02T18:06:22.674981+00:00
2024-06-03T07:01:25.780601+00:00
18
false
\n<!-- Describe your first thoughts on how to solve this problem. -->\n# Approach and Intuition\n<!-- Describe your approach to solving the problem. -->\nWrite Brute Force For the Given Solution.\n\nSince if we apply it over Complete string, it may lead to Time Limit Exceed. So to avoid it we will only Store Indices according to character in map and then remove them accordingly in order to reduce time.\n\nFinally Constructing the final string ans using the elements of map\n\n# Complexity\n- Time complexity: $$O(n*log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n map<char,vector<int>> mp;\n for ( int i = 0 ; i < int(s.size()) ; i++ ) {\n if ( s[i] == \'*\' ) {\n while ( mp.begin()->second.size() == 0 ) {\n mp.erase(mp.begin());\n }\n mp.begin()->second.pop_back();\n }\n else {\n mp[s[i]].emplace_back(i);\n }\n }\n string ans = "";\n vector<char> a(int(s.size()),\'0\');\n for ( auto i : mp ) {\n for ( auto ind : i.second ) {\n a[ind] = i.first;\n }\n }\n for ( auto i : a ) {\n if ( i != \'0\' ) ans += i;\n }\n return ans;\n }\n};\n```\n# Please Upvote if you Liked, Understood the Solution\n\n# Thanks for Reading \uD83D\uDE0A\uD83D\uDE0A\n
1
0
['String', 'Greedy', 'Sorting', 'C++']
0
lexicographically-minimum-string-after-removing-stars
✅✅✅ C++ Easy solution : Beats 100% ---> By min heap
c-easy-solution-beats-100-by-min-heap-by-xh4q
Intuition\nWe have to delete * and the smallest non-\'*\' character to its left. \n# Approach\nFor smallest , Heap only give smallest number in O(1) complexity
arjun-02
NORMAL
2024-06-02T18:01:52.518719+00:00
2024-06-02T18:01:52.518759+00:00
13
false
# Intuition\nWe have to delete * and the smallest non-\'*\' character to its left. \n# Approach\nFor smallest , Heap only give smallest number in O(1) complexity. so, we took heap Data structure. And we have to return as it is order except the deleted one .. so we have to track the index. we push {char,index} in Heap . \n\n# Complexity\n- Time complexity:\nO(n) + O(n) -> O(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass cmp {\n public:\n bool operator()(pair<char,int>&a, pair<char,int>&b){\n if(a.first != b.first){\n return a.first > b.first;\n }\n else return a.second < b.second;\n }\n};\nclass Solution {\npublic:\n string clearStars(string s) {\n priority_queue<pair<char,int>,vector<pair<char,int>>,cmp>pq;\n\n for(int i=0;i<s.size();i++){\n if(s[i]==\'*\'){\n auto top=pq.top(); pq.pop();\n int index=top.second;\n s[index]=\'*\';\n }\n else{\n pq.push({s[i],i});\n }\n }\n\n string ans="";\n for(char ch : s){\n if(ch!=\'*\'){\n ans+=ch;\n }\n }\n \n return ans;\n \n }\n \n};\n```
1
0
['C++']
0
lexicographically-minimum-string-after-removing-stars
Code Using a Custom Class Comparator inside an Ordered Set in C++
code-using-a-custom-class-comparator-ins-0c8e
Approach\nFor getting lexicographically smallest string the main logic is to delete that smallest character which is left to a \'\' character which has greatest
Paras_Punjabi
NORMAL
2024-06-02T14:35:33.475542+00:00
2024-06-02T14:35:33.475569+00:00
9
false
# Approach\nFor getting lexicographically smallest string the main logic is to delete that smallest character which is left to a \'*\' character which has greatest index.\n\n# Complexity\n- Time complexity: $$O(n*log(n))$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\ntemplate <typename T>\nclass comp{\n public:\n bool operator()(T a, T b) const {\n if(a.first == b.first) return a.second > b.second;\n return a.first < b.first;\n }\n};\nclass Solution {\npublic:\n string clearStars(string s) {\n int n = s.size();\n vector<pair<char,int>> arr;\n set<pair<char,int>,comp<pair<char,int>>> st;\n for(int i=0;i<n;i++){\n if(s[i] == \'*\'){\n arr.push_back(*st.begin());\n st.erase(st.begin());\n }\n else{\n st.insert({s[i],i});\n }\n }\n vector<int> idx;\n string ans = "";\n for(auto item : arr){\n idx.push_back(item.second);\n }\n int p = 0;\n sort(idx.begin(),idx.end());\n for(int i=0;i<n;i++){\n if(s[i] == \'*\') continue;\n if(p<idx.size() and idx[p] == i){\n p++;\n }\n else{\n ans+=s[i];\n }\n }\n return ans;\n }\n};\n```
1
0
['Sorting', 'Ordered Set', 'C++']
0
lexicographically-minimum-string-after-removing-stars
Python, easy, using stack and min heap.
python-easy-using-stack-and-min-heap-by-neeky
Using stack and minheap\n\n# Code\n\nfrom heapq import heapify, heappush, heappop\n\nclass Solution:\n def clearStars(self, string: str) -> str:\n s =
idontknowwhodoi
NORMAL
2024-06-02T13:11:33.055910+00:00
2024-06-02T13:11:33.055935+00:00
11
false
Using stack and minheap\n\n# Code\n```\nfrom heapq import heapify, heappush, heappop\n\nclass Solution:\n def clearStars(self, string: str) -> str:\n s = []\n h = []\n heapify(h)\n \n for i in string:\n # print(s, h)\n if i != \'*\':\n s.append(i)\n heappush(h, i)\n else:\n to_remove = heappop(h)\n \n temp_stack = []\n \n while s[-1] != to_remove:\n temp_stack.append(s.pop())\n \n s.pop()\n \n while temp_stack:\n s.append(temp_stack.pop())\n \n return "".join(s)\n```
1
0
['Stack', 'Heap (Priority Queue)', 'Python3']
0
lexicographically-minimum-string-after-removing-stars
c++ solution using set
c-solution-using-set-by-dilipsuthar60-fhnr
\nclass Solution {\npublic:\n string clearStars(string s) {\n int n=s.size();\n vector<bool>visited(n,true);\n set<pair<char,int>>st;\n
dilipsuthar17
NORMAL
2024-06-02T12:41:00.944894+00:00
2024-06-02T12:44:28.953244+00:00
18
false
```\nclass Solution {\npublic:\n string clearStars(string s) {\n int n=s.size();\n vector<bool>visited(n,true);\n set<pair<char,int>>st;\n for(int i=0;i<n;i++){\n if(s[i]==\'*\'&&st.size()){\n auto [ch,index]=*st.begin();\n st.erase(st.begin());\n visited[-index]=false;\n }\n else{\n st.insert({s[i],-i});\n }\n }\n string result="";\n for(int i=0;i<n;i++)\n {\n if(s[i]!=\'*\'&&visited[i]){\n result+=s[i];\n }\n }\n return result;\n }\n};\n```
1
0
['C', 'C++']
0
lexicographically-minimum-string-after-removing-stars
Easy Heap
easy-heap-by-maria_q-x5ap
Complexity\n- Time complexity: O(n*log(n))\n\n- Space complexity: O(n)\n\n# Code\n\nclass Solution:\n def clearStars(self, s: str) -> str:\n heap = []
maria_q
NORMAL
2024-06-02T10:01:21.097996+00:00
2024-06-02T10:01:21.098026+00:00
39
false
# Complexity\n- Time complexity: $$O(n*log(n))$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def clearStars(self, s: str) -> str:\n heap = []\n for i,ch in enumerate(s):\n if ch != \'*\':\n heappush(heap, (ch,-i))\n else:\n heappop(heap)\n \n sett = set(heap)\n\n return \'\'.join(ch for i,ch in enumerate(s) if (ch,-i) in sett)\n```
1
0
['Heap (Priority Queue)', 'Python3']
0
lexicographically-minimum-string-after-removing-stars
Detailed Explanation for Multiple Approaches.
detailed-explanation-for-multiple-approa-d62q
Intuition\n Describe your first thoughts on how to solve this problem. \n\nIn this problem, we are asked to:\n\n1. Remove smallest character in the left side of
ddhira123
NORMAL
2024-06-02T08:28:17.167088+00:00
2024-06-02T08:28:17.167105+00:00
151
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nIn this problem, we are asked to:\n\n1. Remove ***smallest*** character in the left side of `*`.\n2. Get **lexicographically minimum string** possible from the operations.\n\nThus, we need to do **deletion of right-most occurence of smallest character that appears in the left side of `*` in the string**.\n\nSmallest character is about the alphabetic order (a, b, c, d, e, ..., y, z). For example, if we have string `aac*ad*`, then we will do:\n\n1. First `*` appears as 4th character in the string, so we need to remove **rightmost** of **smallest** character before `*` and the `*` from `aac*`, which results `ac`.\n2. Second `*` is at the end of string, then we remove the leftmost `a` from the string `acad*`. Hence, the final result is `acd`.\n\nSo, there are 2 ways to address this problem:\n\n1. Priority Queue\n2. Hash Table + Stack\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n## Priority Queue\n\nWith this container, we can simply get the character to delete every time we encounter `*`. The priority for comparation is:\n\n1. Smallest character in alphabet order.\n2. Biggest index (most recent) of occurences of that character in the string.\n\nPseudocode:\n1. Initialize a priority queue of `pair<char, int>` (pair of char and its occurence, or create a class implementing `Comparable` in Java) with the priority above. \n2. For every character in string `s`:\n 1. If `s[i] == \'*\'`, pop from priority queue.\n 2. Otherwise, push the `<s[i], i>` to priority queue.\n3. Create container for answer with the size of `s`.\n4. For every remaining elements of priority queue, assign the char to their indexes.\n ```\n while(!pq.isEmpty())\n ans[pq.top().i] = pq.pop().ch\n ```\n5. Return the answer. You may need to replace the initialized `\\0` to empty string.\n\n### Example (s = `aac*ad*`)\n\nIn this example, `pq` is the priority queue and top if the left most element.\n\n1. ```\n i = 0, s[i] = \'a\' // push <\'a\', 0>\n pq = [<\'a\', 0>]\n ```\n1. ```\n i = 1, s[i] = \'a\' // push <\'a\', 1>\n pq = [<\'a\', 0>, <\'a\', 1>]\n ```\n1. ```\n i = 2, s[i] = \'c\' // push <\'c\', 2>\n pq = [<\'a\', 0>, <\'a\', 1>, <\'c\', 2>]\n ```\n1. ```\n i = 3, s[i] = \'*\' // pop\n pq = [<\'a\', 0>, <\'c\', 2>]\n ```\n1. ```\n i = 4, s[i] = \'a\' // push\n pq = [<\'a\', 4>, <\'a\', 0>, <\'c\', 2>]\n ```\n1. ```\n i = 5, s[i] = \'d\' // push\n pq = [<\'a\', 4>, <\'a\', 0>, <\'c\', 2>, <\'d\', 5>]\n ```\n1. ```\n i = 6, s[i] = \'*\' // pop\n pq = [<\'a\', 0>, <\'c\', 2>, <\'d\', 5>]\n ```\n1. Reconstruct the string, so it will be `acd` as final answer.\n\n## Hash Table + Stack\n\nThe idea is to store occurences from all characters in the string until we find `*` (Hash Map / Table) and do removal based on the latest element found (last-in-first-out / Stack). \n\nSteps:\n\n1. Initialize a `Map<Character, Stack<Integer>>` container, let\'s name it `m`.\n2. For every character in string `s`:\n 1. If current char `s[i] == \'*\'`:\n 1. Get existing smallest alphabetic character occurence stack from `m`, and pop it out.\n 2. Otherwise, push the occurence index `i` to the stack in `m[s[i]]`. You may need to create new Stack for `s[i]` if it doesn\'t exist in `m`.\n2. For every remaining elements of m, assign the char to their indexes.\n ```\n for key in m.keys():\n while m[key] is not empty():\n ans[m[key].pop()] = key\n ```\n2. Return the answer. You may need to replace the initialized `\\0` to empty string.\n\n### Example (s = `aac*ad*`)\n\nIn this example, the stack is represented by `[]` and top of stack is at the rightmost, before `]`.\n\n1. ```\n i = 0, s[i] = \'a\' // push 0\n m = {\'a\': [0]}\n ```\n1. ```\n i = 1, s[i] = \'a\' // push 1\n m = {\'a\': [0, 1]}\n ```\n1. ```\n i = 2, s[i] = \'c\' // push 2\n m = {\'a\': [0, 1], \'c\': [2]}\n ```\n1. ```\n i = 3, s[i] = \'*\' // pop\n m = {\'a\': [0], \'c\': [2]}\n ```\n1. ```\n i = 4, s[i] = \'a\' // push\n m = {\'a\': [0, 4], \'c\': [2]}\n ```\n1. ```\n i = 5, s[i] = \'d\' // push\n m = {\'a\': [0, 4], \'c\': [2], \'d\': [5]}\n ```\n1. ```\n i = 6, s[i] = \'*\' // pop\n m = {\'a\': [0], \'c\': [2], \'d\': [5]}\n ```\n1. Reconstruct the string, so it will be `acd` as final answer.\n\n# Complexity\n- Time complexity: $$O(n log( n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n## Priority Queue\n\n```Java []\nclass Solution {\n class Char implements Comparable<Char>{\n char c;\n int occ;\n\n public Char(char c, int occ) {\n this.c = c;\n this.occ = occ;\n }\n \n @Override\n public int compareTo(Char that) {\n return this.c - that.c == 0 ? that.occ - this.occ : this.c - that.c; \n }\n }\n public String clearStars(String s) {\n PriorityQueue<Char> pq = new PriorityQueue();\n for(int i=0; i<s.length(); i++) {\n if(s.charAt(i) == \'*\') {\n pq.poll();\n } else {\n pq.offer(new Char(s.charAt(i), i));\n }\n }\n char[] ans = new char[s.length()];\n while(!pq.isEmpty()) {\n ans[pq.peek().occ] = pq.poll().c;\n }\n return new String(ans).replaceAll("\\0", "");\n }\n}\n```\n```c++ []\n#define mp(a, b) make_pair(a, b)\ntypedef pair<char, int> pci;\n\nclass Solution {\npublic:\n string clearStars(string s) {\n auto Compare = [](pci &a, pci &b) {\n return a.first == b.first ? a.second < b.second : a.first > b.first;\n };\n priority_queue<pci, vector<pci>, decltype(Compare)> pq;\n for(int i=0; i<s.length(); i++) {\n if(s[i] == \'*\') {\n pci p = pq.top();\n s[p.second] = \'*\';\n pq.pop();\n } else {\n pq.push(mp(s[i], i));\n }\n }\n string ans = "";\n for(int i=0; i<s.length(); i++) {\n if(s[i] != \'*\') {\n ans += s[i];\n }\n }\n return ans;\n }\n};\n```\n\n## Hash Table + Stack\n\n```Java []\nclass Solution {\n public String clearStars(String s) {\n Map<Character, Stack<Integer>> m = new HashMap();\n for(int i=0; i<s.length(); i++) {\n char c = s.charAt(i);\n if(c == \'*\') {\n for(char ch = \'a\'; ch <= \'z\'; ch++) {\n if(m.get(ch) != null && !m.get(ch).isEmpty()){\n m.get(ch).pop();\n break;\n }\n }\n } else {\n if(!m.containsKey(c))\n m.put(c, new Stack());\n m.get(c).push(i);\n }\n }\n char[] ans = new char[s.length()];\n for(Map.Entry<Character, Stack<Integer>> e : m.entrySet()) {\n while(!e.getValue().isEmpty())\n ans[e.getValue().pop()] = e.getKey();\n }\n return new String(ans).replaceAll("\\0", "");\n }\n}\n```
1
0
['Hash Table', 'Stack', 'Heap (Priority Queue)', 'Java']
0
lexicographically-minimum-string-after-removing-stars
Easy sol^n
easy-soln-by-singhgolu933600-22ep
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
singhgolu933600
NORMAL
2024-06-02T06:38:41.861150+00:00
2024-06-02T06:38:41.861178+00:00
26
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```\nclass Solution {\npublic:\n string clearStars(string s) {\n unordered_map<char,vector<int>>mapping;\n string ans;\n for(int i=0;i<s.size();i++)\n {\n if(s[i]==\'*\')\n {\n for(int j=0;j<26;j++)\n {\n if(mapping.find(\'a\'+j)!=mapping.end())\n {\n s[mapping[\'a\'+j].back()]=\'-\';\n mapping[\'a\'+j].pop_back();\n if(mapping[\'a\'+j].size()==0)\n mapping.erase(\'a\'+j);\n break;\n }\n }\n }\n else\n {\n mapping[s[i]].push_back(i);\n }\n }\n for(int i=0;i<s.size();i++)\n {\n if(s[i]!=\'*\'&&s[i]!=\'-\')\n ans.push_back(s[i]);\n }\n return ans;\n }\n};\n```
1
0
['Hash Table', 'C++']
0
lexicographically-minimum-string-after-removing-stars
Easy C++ O(N*26) solution
easy-c-on26-solution-by-ojasmittal-mdqq
Code\n\nclass Solution {\npublic:\n string clearStars(string s) {\n vector<int>v(26,0);\n int n = s.size();\n string temp = "";\n
OjasMittal
NORMAL
2024-06-02T06:16:28.914483+00:00
2024-06-02T06:16:28.914503+00:00
8
false
# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n vector<int>v(26,0);\n int n = s.size();\n string temp = "";\n for(int i=0;i<n;i++){\n if(s[i]!=\'*\') {\n v[s[i]-\'a\']++;\n temp.push_back(s[i]);\n }\n else{\n char c;\n for(int i=0;i<26;i++){\n if(v[i]>0){\n v[i]--;\n c=i+\'a\';\n break;\n }\n }\n for(int j=temp.size()-1;j>=0;j--){\n if(temp[j]==c){\n temp.erase(j,1);\n break;\n }\n }\n }\n }\n return temp;\n }\n};\n```
1
0
['C++']
0
lexicographically-minimum-string-after-removing-stars
Beats 100% java users | solved using Tree set
beats-100-java-users-solved-using-tree-s-o4aq
\n\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n
Manoj_mk28
NORMAL
2024-06-02T05:46:23.503448+00:00
2024-06-02T05:46:23.503473+00:00
74
false
\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public static String clearStars(String s) {\n TreeSet<Character> set = new TreeSet<>();\n StringBuilder str = new StringBuilder();\n int[] freq = new int[26];\n\n for (char c : s.toCharArray()) {\n if (c == \'*\') {\n remove(str, set, freq);\n } else {\n freq[c - \'a\']++;\n set.add(c);\n str.append(c);\n }\n }\n return str.toString();\n }\n\n public static void remove(StringBuilder sb, TreeSet<Character> set, int[] freq) {\n if (sb.length() == 0) return;\n\n char ch = set.first();\n int lastIndex = sb.lastIndexOf(String.valueOf(ch));\n\n if (lastIndex != -1) {\n int remainingFrequency = --freq[ch - \'a\'];\n\n if (remainingFrequency == 0) {\n set.pollFirst();\n }\n sb.deleteCharAt(lastIndex);\n }\n }\n}\n```
1
0
['Ordered Set', 'Java']
0
lexicographically-minimum-string-after-removing-stars
Easy Java Solution || Sorting || Beats 100%
easy-java-solution-sorting-beats-100-by-81vg6
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
ravikumar50
NORMAL
2024-06-02T05:12:55.211749+00:00
2024-06-02T05:12:55.211776+00:00
83
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```\nclass Solution {\n public String clearStars(String s) {\n int n = s.length();\n\n ArrayList<Integer> arr[] = new ArrayList[26];\n for(int i=0; i<26; i++) arr[i] = new ArrayList<>();\n for(int i=0; i<n; i++){\n char ch = s.charAt(i);\n\n if(ch==\'*\'){\n for(int k=0; k<26; k++){\n if(arr[k].size()!=0){\n arr[k].remove(arr[k].size()-1);\n break;\n }\n }\n }else{\n arr[ch-\'a\'].add(i);\n }\n }\n\n ArrayList<int[]> a = new ArrayList<>();\n for(int i=\'a\'; i<=\'z\'; i++){\n for(var x : arr[i-\'a\']){\n a.add(new int[]{i,x});\n }\n }\n\n StringBuilder ans = new StringBuilder();\n \n Collections.sort(a,(x,y)->x[1]-y[1]);\n \n for(var x : a){\n \n ans.append((char)x[0]);\n }\n return ans.toString();\n }\n}\n```
1
0
['Java']
0
lexicographically-minimum-string-after-removing-stars
Easy c++ solution ||
easy-c-solution-by-sumitdarshanala-eciz
Intuition\n Describe your first thoughts on how to solve this problem. \n- Data Structure\n\n map> mp;\n- use\n\n for storing the index of charact
sumitdarshanala
NORMAL
2024-06-02T05:10:57.762436+00:00
2024-06-02T09:52:36.096131+00:00
48
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Data Structure\n\n map<char,vector<int>> mp;\n- use\n\n for storing the index of characters and as \n map will sort according to key therefore \n mp.begin() will have the smallest character \n and to get lexi.. smallest string we have to\n remove the rightmost char outoff the character\n which are available to remove which is stored in\n the vector\'s last index .\n- Therefore we have everything to proceed .\n- Steps:\n\n Initialization: Create a map mp to store\n characters and their indices.\n- Processing:\n \n Iterate through s.\n - If the character is \'*\':\n Mark it as \'1\'.\n If mp is not empty,\n remove the smallest character \n present at mp.begin()\n and mark it as \'1\' in string. And\n remember to remove the index which\n is removed from string.\n - Otherwise,\n add the character and \n its index to mp.\n- Construct Result: \n\n Build the result string by excluding \n characters marked as \'1\'.\n\n- Example:\n\n For input "ab*c*d*e", the processing\n steps will transform it to "11111d1e",\n and the final result will be "de".\n\n\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 O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N)\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n int n = s.size();\n map<char,vector<int>> mp;\n for(int i = 0;i < s.size(); i++){\n if(s[i] == \'*\'){\n s[i] = \'1\';\n if(mp.size() == 0)continue;\n \n auto it = mp.begin();\n char ch = mp.begin()->first;\n \n \n int idx = mp.begin()->second[mp.begin()->second.size()-1];\n mp.begin()->second.pop_back();\n if(mp.begin()->second.size() == 0)mp.erase(ch);\n s[idx] = \'1\';\n }else{\n mp[s[i]].push_back(i);\n }\n }\n string ans = "";\n for(auto x : s){\n if(x != \'1\')\n ans += x;\n }\n return ans;\n\n }\n};\n```
1
0
['String', 'Ordered Map', 'C++']
0
lexicographically-minimum-string-after-removing-stars
C++ || 2D VECTOR
c-2d-vector-by-abhishek6487209-u4h7
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
Abhishek6487209
NORMAL
2024-06-02T04:51:46.766728+00:00
2024-06-02T04:51:46.766749+00:00
162
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```\nclass Solution {\npublic:\n string clearStars(string s){ \n vector<vector<int>> ch(26);\n vector<int> a(s.size(),1);\n for(int i=0;i<s.size();i++){\n if(s[i]==\'*\'){\n a[i]=0;\n for(int j=0;j<26;j++){\n if(ch[j].size()>0){\n a[ch[j].back()]=0;\n ch[j].pop_back();\n break;\n }\n }\n } else{\n ch[s[i]-\'a\'].push_back(i);\n }\n }\n string ans="";\n for(int i=0;i<s.size();i++){\n if(a[i]) {\n ans+=s[i];\n }\n }\n return ans;\n }\n};\n```
1
0
['C++']
1
lexicographically-minimum-string-after-removing-stars
Simply Explained Python Solution - Priority Queue and Heap
simply-explained-python-solution-priorit-x3s4
This question is kind of tricky. Every * means that we must remove a letter that is to its left. Not only that, but the removed letter has to be the smallest on
Alan6458
NORMAL
2024-06-02T04:50:16.789493+00:00
2024-06-02T04:50:16.789514+00:00
22
false
This question is kind of tricky. Every `*` means that we must remove a letter that is to its left. Not only that, but the removed letter has to be the *smallest* one to its left, and also we must return the *lexicographically smallest solution*.\n\nSo, how do we do this?\n\nLet\'s work it out.\n\nIf we iterate through the string and check to the left of every `*`, it\'s going to cost us a lot of precious time.\n\nIn addition, we need the lexicographically smallest string. This means that when we sort a pool of all possible solutions by alphabetical order, what we return must be the first. We can achieve this by removing the *rightmost* letter that we can. By this, I mean that if we take the testcase `aaba*`, we remove the third "a", and by doing this, we get `aab`. The other possible solutions are both `aba`, which is lexicographically *larger* than `aab`.\n\nWhat we could do is to have two variables to track the index and value of a character. If we encounter a character that is smaller or the same as the previous smallest character we encountered, we replace both variables with new values. This guarantees the character we store when we encounter our next `*` can be removed to create the lexicographically smallest output, but there is a huge problem behind this.\n\nTake the testcase `aaba**`. This testcase requires you to now either go over the entire list again, or to store a *second* character value! The testcase `aaba***` requires you to store *three*! Going over the list again requires too much time, so we *must* store the characters.\n\nWouldn\'t it be great if we had a datatype similar to a list, but whenever we put something in it, it sorts itself?\n\nWe have something like that! It\'s called a **priority queue**.\n\nIn Python, we can use the heap to implement a priority queue. This uses the heapq library.\n\nWhen we encounter a letter, we put it into the priority queue, which sorts the character by its value and index. Then, when we see a `*`, we can just pull the smallest character with the largest index out of the priority queue, and then remove it from the string.\n\n```\nimport heapq\nclass Solution:\n def clearStars(self, s: str) -> str:\n # r is the list of indices to remove at the end\n r = set()\n # creates priority queue\n sm = []\n heapq.heapify(sm)\n for i, v in enumerate(s):\n # Takes something from our heap if we face a "*"\n if v == "*":\n # marks what indices to remove at the end\n r.add(i)\n r.add(-heapq.heappop(sm)[1])\n else:\n # Otherwise, adds the character to our heap\n # Heap is smallest out first\n # This is good for our character, but not for the index\n # So, we make larger indices smallest by negation\n heapq.heappush(sm, (v, -i))\n # If it should be removed, don\'t include it in the string we return\n return "".join(s[i] for i in range(len(s)) if i not in r)\n```
1
1
['Python3']
1
lexicographically-minimum-string-after-removing-stars
JAVA | O(N) ~ O(N * log(26))| Beats 100% java users | Simple TreeMap Solution
java-on-on-log26-beats-100-java-users-si-mwcc
\npublic static String clearStars(String s) {\n TreeMap<Integer, Stack<Integer>> tm = new TreeMap<>();\n int[]del = new int[s.length()];\n
pankaj__yadav
NORMAL
2024-06-02T04:41:26.662852+00:00
2024-06-02T04:46:36.230843+00:00
4
false
```\npublic static String clearStars(String s) {\n TreeMap<Integer, Stack<Integer>> tm = new TreeMap<>();\n int[]del = new int[s.length()];\n for(int i = 0; i<s.length(); i++){\n if(s.charAt(i) != \'*\'){\n tm.putIfAbsent(s.charAt(i) + \'0\', new Stack<>());\n tm.get(s.charAt(i) + \'0\').add(i);\n continue;\n }\n del[i] = 1;\n Integer smallestChar = tm.ceilingKey(\'a\' + \'0\');\n if(smallestChar==null)continue;\n Stack<Integer> st = tm.get(smallestChar);\n del[st.pop()] = 1;\n if(st.isEmpty()){\n tm.remove(smallestChar);\n } \n \n }\n StringBuilder result = new StringBuilder();\n for(int i = 0; i<del.length; i++){\n if(del[i] == 1)continue;\n result.append(s.charAt(i));\n } \n return result.toString();\n }\n```
1
1
['Tree', 'Binary Tree']
0
lexicographically-minimum-string-after-removing-stars
Python3 | Simple stack without heap
python3-simple-stack-without-heap-by-red-3wcs
After investigation, we found if there is a smallest char, delete it from the rightmost of the current string would keep the current string as lexicographically
redchokeberry
NORMAL
2024-06-02T04:28:28.232370+00:00
2024-06-02T04:42:31.841017+00:00
179
false
After investigation, we found if there is a smallest char, delete it from the rightmost of the current string would keep the current string as lexicographically minimum string. We can use a stack to track the index of each character and pop from it to get the rightmost index.\n\nHence when traverse the string, we use following variable\n- `char_index` to record the index occrance of each character\n- `smallest_c` to record the smallest character so far\n- `current_s` to record all the character and set the deleted character as `\'\'` so that we can join them to get the anwser in the end\n\nTC `O(n)` the `for` loop iterate the length of string times\nSC `O(n)` the `current_s` record at most the length of string elements\n\n```\nclass Solution:\n def clearStars(self, s: str) -> str:\n\n\t\t# use list to mutate char\n current_s = [] \n smallest_c = \'\'\n char_index = defaultdict(list)\n\n for i in range(len(s)):\n c = s[i]\n \n current_s.append(c)\n if c != \'*\':\n if not smallest_c or ord(c) < ord(smallest_c):\n smallest_c = c\n\n char_index[c].append(i)\n else:\n index = char_index[smallest_c].pop()\n current_s[index] = \'\'\n\n\t\t\t\t# update smallest_c when there is no more the original one \n if len(char_index[smallest_c]) == 0:\n del char_index[smallest_c]\n \n keys = char_index.keys()\n\n if keys:\n smallest_c = min(keys)\n else:\n\t\t\t\t\t\t# reset smallest_c to \'\' so that we can set it to another one later\n smallest_c = \'\'\n return \'\'.join(\'\' if c == \'*\' else c for c in current_s)\n \n```
1
0
['Stack', 'Python3']
1
lexicographically-minimum-string-after-removing-stars
Easy C++ | Store Prefix Alphabets index | Linear Time | Lexicographically Minimum String
easy-c-store-prefix-alphabets-index-line-3s6o
\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n
JeetuGupta
NORMAL
2024-06-02T04:27:02.878610+00:00
2024-06-02T04:28:15.395317+00:00
167
false
\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n vector<vector<int>> cnt(26, vector<int>(0));\n for(int i = 0; i<s.size(); i++){\n if(s[i] == \'*\'){\n for(int j = 0; j<26; j++){\n if(cnt[j].size() > 0){\n s[cnt[j].back()] = \'0\';\n cnt[j].pop_back();\n break;\n }\n }\n }else{\n int index = s[i] - \'a\';\n cnt[index].push_back(i);\n }\n }\n\n string ans = "";\n for(int i = 0; i<s.size(); i++){\n if(s[i] == \'*\' || s[i] == \'0\') continue;\n else ans += s[i];\n }\n\n return ans;\n }\n};\n```
1
0
['C++']
1
lexicographically-minimum-string-after-removing-stars
C++ Solution || Only Array simple approach || O(n)
c-solution-only-array-simple-approach-on-rx3n
\n Describe your first thoughts on how to solve this problem. \n\n# Approach--> \n### Just have a array where we will strore the index of stars and alphabet to
Shubham_Redoc
NORMAL
2024-06-02T04:23:46.503932+00:00
2024-06-02T04:24:24.850162+00:00
19
false
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach--> \n### Just have a array where we will strore the index of stars and alphabet to be deleted from string as 1 so that at last we can form our resultant string out of it. \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(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n vector<int> vis(26,0);\n string ans="";\n vector<vector<int>> pos(26);\n int n=s.size();\n vector<int> vec(n,0);\n for(int i=0;i<s.size();i++){\n if(s[i]==\'*\'){\n int n=0;\n for(int c=0;c<26;c++){\n if(vis[c]>=1){\n n=c;\n break;\n }\n }\n char ch= n +\'a\';\n int ind=pos[n][pos[n].size()-1];\n vec[ind]=1;vec[i]=1;\n vis[n]--;\n pos[n].pop_back();\n }\n else{\n vis[s[i]-\'a\']++;\n pos[s[i]-\'a\'].push_back(i);\n }\n }\n for(int i=0;i<n;i++){\n if(vec[i]==0){\n ans+=s[i];\n }\n }\n return ans;\n }\n};\n```
1
0
['Array', 'String', 'C++']
1
lexicographically-minimum-string-after-removing-stars
C++ || Priority-queue || EASY-PEASY
c-priority-queue-easy-peasy-by-spa111-v453
\n\n# Code\n\nclass compare {\npublic:\n bool operator()(pair<char, int> a, pair<char, int> b) {\n if(a.first == b.first)\n return a.second
SPA111
NORMAL
2024-06-02T04:14:44.736730+00:00
2024-06-02T04:14:44.736766+00:00
366
false
\n\n# Code\n```\nclass compare {\npublic:\n bool operator()(pair<char, int> a, pair<char, int> b) {\n if(a.first == b.first)\n return a.second < b.second;\n else \n return a.first > b.first;\n }\n};\n\nclass Solution { \npublic:\n string clearStars(string s) {\n int len = s.length();\n priority_queue<pair<char, int>, vector<pair<char, int>>, compare> pq;\n string ans;\n \n for(int i = 0; i < len; i++) {\n if(s[i] != \'*\')\n pq.push({s[i], i});\n else {\n char smallCh = pq.top().first;\n int smallIdx = pq.top().second;\n pq.pop();\n s[smallIdx] = s[i] = \'#\';\n }\n \n }\n \n for(auto ch : s) {\n if(ch != \'#\')\n ans.push_back(ch);\n }\n \n return ans;\n }\n};\n```
1
0
['Heap (Priority Queue)', 'C++']
1
lexicographically-minimum-string-after-removing-stars
[JAVA] O(N) solution
java-on-solution-by-wall__e-d2ak
Intuition\n Describe your first thoughts on how to solve this problem. \n1. Keep track of the positions of all letters\n2. Once a * is encountered, find the fir
wall__e
NORMAL
2024-06-02T04:11:48.858436+00:00
2024-06-02T04:17:16.802664+00:00
14
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Keep track of the positions of all letters\n2. Once a `* ` is encountered, find the first letter alphabetically and remove the last position. Save the removed position to a set.\n3. Loop string again and ignore the removed letters and stars\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(26 * N) -> O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String clearStars(String s) {\n List<Integer>[] map = new ArrayList[26];\n Set<Integer> set = new HashSet<>();\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c != \'*\') {\n if (map[c - \'a\'] == null) {\n map[c - \'a\'] = new ArrayList<Integer>();\n }\n map[c - \'a\'].add(i);\n } else {\n for (int j = 0; j < 26; j++) {\n if (map[j] == null || map[j].size() == 0) continue;\n set.add(map[j].get(map[j].size() - 1));\n map[j].remove(map[j].size() - 1);\n break;\n }\n }\n }\n \n var sb = new StringBuilder();\n for (int i = 0; i < s.length(); i++) {\n if (set.contains(i) || s.charAt(i) == \'*\') continue;\n sb.append(s.charAt(i));\n }\n return sb.toString();\n }\n}\n```
1
0
['Java']
0
lexicographically-minimum-string-after-removing-stars
JAVA SOLUTION || USING STACK
java-solution-using-stack-by-viper_01-iabe
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
viper_01
NORMAL
2024-06-02T04:11:40.211852+00:00
2024-06-02T04:11:40.211875+00:00
84
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```\nclass Solution {\n public String clearStars(String s) {\n if(s.indexOf(\'*\') == -1) return s;\n \n char a[] = s.toCharArray();\n \n Stack<Integer> stk = new Stack<>();\n Stack<Integer> stk1 = new Stack<>();\n \n for(int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n \n if(c == \'*\') {\n \n a[stk.pop()] = \' \';\n \n continue;\n }\n \n while(!stk.isEmpty() && s.charAt(stk.peek()) < c ) {\n stk1.push(stk.pop());\n }\n \n stk.push(i);\n \n while(!stk1.isEmpty()) {\n stk.push(stk1.pop());\n }\n }\n \n StringBuilder sb = new StringBuilder("");\n \n for(char c : a) {\n if(c != \' \' && c != \'*\') {\n sb.append(c);\n }\n }\n \n return sb.toString();\n }\n}\n```
1
0
['Stack', 'Java']
0
lexicographically-minimum-string-after-removing-stars
C++ O(N*26)
c-on26-by-sumit1906-kipf
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
sumit1906
NORMAL
2024-06-02T04:11:03.208648+00:00
2024-06-02T04:11:03.208680+00:00
94
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```\nclass Solution {\npublic:\n string clearStars(string &s)\n {\n // vector<int> pos(26,-1);\n vector<vector<int>> pos(26,vector<int>(0));\n for(int i=0;i<s.length();i++)\n {\n if(s[i]!=\'*\')\n pos[s[i]-\'a\'].push_back(i);\n \n \n if(s[i]==\'*\')\n {\n for(int i=0;i<26;i++)\n {\n if(pos[i].size()>0)\n {\n s[pos[i].back()]=\'@\';\n pos[i].pop_back();\n // pos[i]=-1;\n break;\n }\n \n}\n \n}\n}\n string ans="";\n for(auto a:s)\n {\n if(a!=\'@\'&&a!=\'*\')\n ans.push_back(a);\n }\n return ans;\n }\n};\n```
1
0
['C++']
1