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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
reformat-the-string | Python Simple and Easy Explained Solution | python-simple-and-easy-explained-solutio-qrty | \nclass Solution:\n def reformat(self, s: str) -> str:\n # Create separate arrays for letters and digits:\n numbers = [c for c in s if c.isdigi | yehudisk | NORMAL | 2020-12-18T12:31:33.780294+00:00 | 2020-12-18T12:31:33.780333+00:00 | 455 | false | ```\nclass Solution:\n def reformat(self, s: str) -> str:\n # Create separate arrays for letters and digits:\n numbers = [c for c in s if c.isdigit()]\n letters = [c for c in s if c.isalpha()]\n\n # If there are too many digits or letters, return "":\n if abs(len(numbers) - len(letters)) > 1:\n return ""\n \n res, i = "", 0\n # If there are more letters than digits, add one letter in the beginning:\n if len(letters) > len(numbers):\n res += letters[-1]\n \n while i < len(numbers) and i < len(letters):\n res += numbers[i]\n res += letters[i]\n i+=1\n \n # If there are more digits than letters, add one digit at the end:\n if len(numbers) > len(letters):\n res += numbers[-1]\n \n return res\n```\n**Like it? please upvote...** | 6 | 0 | ['Python'] | 0 |
reformat-the-string | [Java] Simple O(n) solution | java-simple-on-solution-by-spirit_obi-bcbu | \npublic String reformat(String s) {\n\tList<Character> nums = new ArrayList<Character>();\n\tList<Character> alph = new ArrayList<Character>();\n\n\tfor (int i | spirit_obi | NORMAL | 2020-11-18T05:58:14.120493+00:00 | 2020-11-18T05:58:14.120539+00:00 | 805 | false | ```\npublic String reformat(String s) {\n\tList<Character> nums = new ArrayList<Character>();\n\tList<Character> alph = new ArrayList<Character>();\n\n\tfor (int i = 0; i < s.length(); i++) {\n\t\tif (Character.isDigit(s.charAt(i)))\n\t\t\tnums.add(s.charAt(i));\n\t\telse\n\t\t\talph.add(s.charAt(i));\n\t}\n\n\tif (Math.abs(nums.size() - alph.size()) > 1)\n\t\treturn "";\n\n\tStringBuilder sb = new StringBuilder();\n\tif (nums.size() >= alph.size()) {\n\t\tfor (int i = 0; i < nums.size(); i++) {\n\t\t\tsb.append(nums.get(i));\n\t\t\tif (i < alph.size())\n\t\t\t\tsb.append(alph.get(i));\n\t\t}\n\t}else{\n\t\tfor (int i = 0; i < alph.size(); i++) {\n\t\t\tsb.append(alph.get(i));\n\t\t\tif (i < nums.size())\n\t\t\t\tsb.append(nums.get(i));\n\t\t}\n\t}\n\treturn sb.toString();\n}\n``` | 6 | 0 | ['Java'] | 1 |
reformat-the-string | 5-line Easy Python solution with explanation | 5-line-easy-python-solution-with-explana-0cd0 | Explanation:\n\n1) d and c are list of digits and non-digits respectively.\n\n2) We return False if their (c and d) difference in length is greater than one \n\ | _xavier_ | NORMAL | 2020-04-19T04:07:44.170770+00:00 | 2020-04-22T04:05:41.781597+00:00 | 397 | false | **Explanation:**\n\n**1)** **d** and **c** are list of digits and non-digits respectively.\n\n**2)** We return False if their (c and d) difference in length is greater than one \n\n**3)** To see why to use **zip_longest** instead of **zip** see below example:\n\n\t\tzip([2, 1], [\'a\']) ----> ((2, \'a\'))\n\t\tzip_longest([2, 1], [\'a\'], fillvalue=\'\') ----> ((2, \'a\'), (1, \'\'))\n\nAs you see zip acts based on the shortest iterable an zip_longest acts based on the longest iterable which is the case e are looking for in this problem.\n\n**4)** In the "return" line we concatenate them and if *None* is present we change it to \'\' to prevent exception\n\n```\nclass Solution:\n def reformat(self, s):\n d = [a for a in s if a.isdigit()]\n c = [a for a in s if a.isalpha()]\n if abs(len(c) - len(d)) > 1: return \'\'\n if len(d) > len(c): c, d = d, c\n return "".join(map(lambda x: x[0] + x[1], zip_longest(c, d, fillvalue=\'\')))\n```\n\n**Update**: I have updated the code by adding fillvalue parameter to zip_longest. Thanks [https://leetcode.com/rmoskalenko](http://) for his great obeservation resulting in improving the code. See comment below for further explanation.\n | 6 | 3 | [] | 5 |
reformat-the-string | [Python] simple, self explanatory solution, beats 100% | python-simple-self-explanatory-solution-bx4gf | ```class Solution(object):\n def reformat(self, s):\n """\n :type s: str\n :rtype: str\n """\n a=[]\n n=[]\n | manasswami | NORMAL | 2020-04-21T10:58:36.422758+00:00 | 2020-04-21T10:58:36.422795+00:00 | 370 | false | ```class Solution(object):\n def reformat(self, s):\n """\n :type s: str\n :rtype: str\n """\n a=[]\n n=[]\n s= list(s)\n length = len(s)\n for i in s:\n if i.isalpha():\n a.append(i)\n else:\n n.append(i)\n dif = len(a)-len(n) \n if abs(dif) > 1:\n return ""\n s=[]\n #if length%2==0:\n \n \n if dif > 0:\n for i in range(length/2):\n if a and n:\n s.append(a[i])\n s.append(n[i])\n s.append(a[-1])\n elif dif < 0:\n for i in range(length/2):\n if a and n:\n s.append(n[i])\n s.append(a[i])\n s.append(n[-1])\n else:\n for i in range(length/2):\n if a and n:\n s.append(n[i])\n s.append(a[i])\n \n return \'\'.join(s)\n | 5 | 1 | [] | 0 |
reformat-the-string | simple and easy C++ solution 😍❤️🔥 | simple-and-easy-c-solution-by-shishirrsi-pxjl | if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n\n#include<bits/stdc++.h>\nclass Solution {\npublic:\n string reformat(string s) \n {\n | shishirRsiam | NORMAL | 2024-05-22T05:20:43.212851+00:00 | 2024-05-22T05:20:43.212886+00:00 | 301 | false | # if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n```\n#include<bits/stdc++.h>\nclass Solution {\npublic:\n string reformat(string s) \n {\n string digit, ch;\n for(char c:s)\n {\n if(isdigit(c)) digit += c;\n else ch += c;\n }\n int n = digit.size(), m = ch.size(), i = 0;\n if(abs(n - m) > 1) return "";\n \n string ans;\n bool flag = true;\n if(n < m) flag = !flag;\n\n while(i < n and i < m)\n {\n if(flag)\n {\n ans += digit[i];\n ans += ch[i];\n }\n else \n {\n ans += ch[i];\n ans += digit[i];\n }\n i++;\n }\n\n if(n != m) ans += (flag ? digit.back() : ch.back());\n\n return ans;\n }\n};\n``` | 4 | 0 | ['String', 'Simulation', 'C++'] | 4 |
reformat-the-string | JS very easy solution | js-very-easy-solution-by-kunkka1996-7q19 | \nconst regexNumber = /^[0-9]$/;\nvar reformat = function(s) {\n const letters = [];\n const numbers = [];\n\n for (let i = 0; i < s.length; i++) {\n | kunkka1996 | NORMAL | 2022-10-11T10:21:40.202908+00:00 | 2022-10-11T10:21:40.202945+00:00 | 718 | false | ```\nconst regexNumber = /^[0-9]$/;\nvar reformat = function(s) {\n const letters = [];\n const numbers = [];\n\n for (let i = 0; i < s.length; i++) {\n if(regexNumber.test(s[i])) {\n numbers.push(s[i]);\n } else {\n letters.push(s[i]);\n }\n }\n \n if (Math.abs(letters.length - numbers.length) > 1) return \'\';\n let output = \'\';\n for (let i = 0; i < s.length/2; i++) {\n if (letters.length > numbers.length) {\n output += letters[i];\n output += numbers[i] || \'\';\n } else {\n output += numbers[i];\n output += letters[i] || \'\';\n }\n }\n return output;\n}\n``` | 4 | 0 | ['JavaScript'] | 0 |
reformat-the-string | Java easiest to understand | java-easiest-to-understand-by-yelhsabana-kvpi | i separate my helper function from the main to make the logic simpler and clearer\n\nclass Solution {\n public String reformat(String s) {\n List<Char | yelhsabananah | NORMAL | 2020-04-20T03:13:21.589425+00:00 | 2020-04-20T03:13:21.589469+00:00 | 565 | false | i separate my helper function from the main to make the logic simpler and clearer\n```\nclass Solution {\n public String reformat(String s) {\n List<Character> str = new ArrayList<>(), nums = new ArrayList<>();\n for (char c : s.toCharArray()) {\n if (Character.isDigit(c)) {\n nums.add(c);\n } else {\n str.add(c);\n }\n }\n //this is how i check my corner case, their lengths can\'t differ by more than 2\n int strlen = str.size(), numlen = nums.size();\n if (Math.abs(strlen - numlen) >= 2) {\n return "";\n }\n \n if (strlen < numlen) {\n return print(nums, str);\n }\n return print(str, nums);\n }\n\n //first list should always be the longer one, second list is the shorter one\n private String print(List<Character> l1, List<Character> l2) {\n int idx = 0;\n StringBuilder sb = new StringBuilder();\n while (idx < l2.size()) {\n sb.append(l1.get(idx));\n sb.append(l2.get(idx++));\n }\n while (idx < l1.size()) {\n sb.append(l1.get(idx++));\n }\n return sb.toString();\n }\n}\n``` | 4 | 1 | [] | 0 |
reformat-the-string | C++ Simplest intuitive solution | c-simplest-intuitive-solution-by-hammerh-9kro | ```\nclass Solution {\npublic:\n string reformat(string s) {\n string str1, str2; // str1 will store letters and str2 will store digits\n \n | hammerhead09 | NORMAL | 2020-04-19T06:52:27.622485+00:00 | 2020-04-19T06:59:06.393240+00:00 | 500 | false | ```\nclass Solution {\npublic:\n string reformat(string s) {\n string str1, str2; // str1 will store letters and str2 will store digits\n \n for (auto &ch : s)\n if (!isdigit(ch))\n str1 += ch;\n else\n str2 += ch;\n \n int diff = str1.length() - str2.length();\n if (abs(diff) > 1)\n return ""; \n \n // ensure str1 always contains the larger string\n if (str1.length() < str2.length())\n swap(str1, str2);\n \n string result;\n int i = 0, j = 0;\n bool toogleFlag = true;\n \n while (i < str1.length() or j < str2.length()) {\n if (toogleFlag)\n result += str1[i++];\n else\n result += str2[j++];\n \n toogleFlag = !toogleFlag;\n }\n \n return result;\n }\n}; | 4 | 3 | [] | 1 |
reformat-the-string | Javascript segregate alphabets and numbers Solution | javascript-segregate-alphabets-and-numbe-abjt | \nvar reformat = function(s) {\n var nums = [];\n var alph = [];\n var res = [];\n for(var i=0;i<s.length;i++){\n if(s[i]>=\'0\' && s[i]<=\'9 | seriously_ridhi | NORMAL | 2020-04-19T05:13:02.956609+00:00 | 2020-04-19T05:13:30.829268+00:00 | 551 | false | ```\nvar reformat = function(s) {\n var nums = [];\n var alph = [];\n var res = [];\n for(var i=0;i<s.length;i++){\n if(s[i]>=\'0\' && s[i]<=\'9\'){\n nums.push(s[i]);\n }else{\n alph.push(s[i]);\n }\n }\n if(Math.abs(nums.length-alph.length)>1){\n return "";\n }\n if(nums.length>alph.length){\n while(nums.length>1){\n res.push(nums.shift());\n res.push(alph.shift());\n }\n res.push(nums.shift());\n }\n else if(nums.length<alph.length){\n while(alph.length>1){\n res.push(alph.shift());\n res.push(nums.shift());\n }\n res.push(alph.shift());\n }else{\n while(alph.length){\n res.push(alph.shift());\n res.push(nums.shift());\n }\n }\n\treturn res.join("");\n};\n``` | 4 | 0 | ['JavaScript'] | 1 |
reformat-the-string | JavaScript Beginner-level code is very simple to understand | javascript-beginner-level-code-is-very-s-y6kl | 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 | althaff | NORMAL | 2024-08-10T20:29:38.975751+00:00 | 2024-08-10T20:29:38.975778+00:00 | 148 | 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} s\n * @return {string}\n */\nvar reformat = function(s) {\n\n let digit = []\n let char = []\n\n for(let c of s){\n if(!Number(c) && 0!=c){\n char.push(c)\n }else{\n digit.push(c)\n }\n }\n let len = digit.length - char.length\n if( len==-1 || len==1 || len==0 ){\n let newstr = []\n let max = Math.max( digit.length , char.length )\n if(digit.length === max){\n for(let i=0 ; i<max ; i++){\n newstr.push(digit[i] , char[i])\n }\n return newstr.join(\'\')\n }else{\n for(let i=0 ; i<max ; i++){\n newstr.push(char[i] , digit[i])\n }\n return newstr.join(\'\')\n }\n\n }else{\n return ""\n }\n};\n``` | 3 | 0 | ['JavaScript'] | 1 |
reformat-the-string | 100% FAST C++ BEST SOLUTION 🤩 | 100-fast-c-best-solution-by-harshitsachd-ru3v | 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\n# Complexity\n- T | harshitsachdeva1219 | NORMAL | 2023-04-08T07:24:34.869171+00:00 | 2023-06-25T17:03:03.352105+00:00 | 546 | 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\n# Complexity\n- Time complexity: O(size of string)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(size of string)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\npublic:\n string reformat(string s) {\n vector<char> alpha;\n vector<char> numbers;\n // Creating a vector for storing alpha and numeric separately\n for(int i=0 ; i<s.size() ; i++)\n {\n if(s[i] >= \'a\' && s[i] <= \'z\'){\n alpha.push_back(s[i]);\n }\n else if(s[i] >= \'0\' && s[i] <= \'9\'){\n numbers.push_back(s[i]);\n }\n }\n string ans = "";\n int m = alpha.size();\n int n = numbers.size();\n // The number of alpha and numeric should be either equal or differ by 1 to make string valid\n if(abs(m-n) <= 1){\n if(m>=n){\n int i;\n for(i=0 ; i<n ; i++)\n {\n ans += alpha[i];\n ans += numbers[i];\n }\n if(m != n){\n ans += alpha[i];\n } \n }\n else{\n int i;\n for(i=0 ; i<m ; i++)\n {\n ans += numbers[i];\n ans += alpha[i]; \n }\n ans += numbers[i];\n }\n \n return ans; \n }\n // else string is invalid\n return ans;\n }\n};\n``` | 3 | 0 | ['String', 'C++'] | 1 |
reformat-the-string | Go solution that beats 100% | go-solution-that-beats-100-by-tuanbieber-2bfa | \nfunc reformat(s string) string {\n\talphabet, alphabetCount := make([]byte, 26), 0\n\tdigit, digitCount := make([]byte, 10), 0\n\tstr := make([]byte, len(s))\ | tuanbieber | NORMAL | 2022-08-22T09:11:08.268160+00:00 | 2022-08-22T09:11:08.268193+00:00 | 324 | false | ```\nfunc reformat(s string) string {\n\talphabet, alphabetCount := make([]byte, 26), 0\n\tdigit, digitCount := make([]byte, 10), 0\n\tstr := make([]byte, len(s))\n\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] >= \'a\' && s[i] <= \'z\' {\n\t\t\talphabet[s[i]-\'a\']++\n\t\t\talphabetCount++\n\t\t} else {\n\t\t\tdigit[s[i]-\'0\']++\n\t\t\tdigitCount++\n\t\t}\n\t}\n\n\tif alphabetCount != digitCount && alphabetCount != digitCount+1 && alphabetCount+1 != digitCount {\n\t\treturn ""\n\t}\n\t\n toggle := 1\n \n if alphabetCount > digitCount {\n toggle = 0\n }\n\n for i := 0; i < len(s); i++ {\n if i%2 == toggle {\n for j := 0; j < 26; j++ {\n if alphabet[j] > 0 {\n str[i] = \'a\' + byte(j)\n alphabet[j]--\n break\n }\n }\n } else {\n for j := 0; j < 10; j++ {\n if digit[j] > 0 {\n str[i] = \'0\' + byte(j)\n digit[j]--\n break\n }\n }\n }\n }\n\n\treturn string(str)\n}\n\n``` | 3 | 0 | ['Go'] | 1 |
reformat-the-string | Using itertools.zip_longest (Python 3) | using-itertoolszip_longest-python-3-by-e-muce | Here\'s an approach similar to other ones, but using itertools.zip_longest instead of zip:\n\nclass Solution:\n def reformat(self, s: str) -> str:\n n | emwalker | NORMAL | 2021-11-28T22:41:31.933819+00:00 | 2021-11-28T22:41:31.933852+00:00 | 119 | false | Here\'s an approach similar to other ones, but using `itertools.zip_longest` instead of `zip`:\n```\nclass Solution:\n def reformat(self, s: str) -> str:\n nums = [c for c in s if c.isnumeric()]\n alph = [c for c in s if c.isalpha()]\n \n if abs(len(nums) - len(alph)) > 1:\n return \'\'\n \n a, b = (nums, alph) if len(nums) <= len(alph) else (alph, nums)\n return \'\'.join(c for pair in itertools.zip_longest(b, a) for c in pair if c)\n``` | 3 | 0 | ['Python3'] | 0 |
reformat-the-string | Simple 2 array JavaScript solution | simple-2-array-javascript-solution-by-at-qaqt | \nvar reformat = function(s) {\n const strArr = [];\n\tconst numArr = [];\n let str = \'\';\n \n for(let i = 0; i < s.length; i++) {\n if(isN | AT34007 | NORMAL | 2021-09-10T07:41:35.978204+00:00 | 2021-09-10T07:41:35.978249+00:00 | 179 | false | ```\nvar reformat = function(s) {\n const strArr = [];\n\tconst numArr = [];\n let str = \'\';\n \n for(let i = 0; i < s.length; i++) {\n if(isNaN(s[i])) {\n strArr.push(s[i]);\n }\n else {\n numArr.push(s[i]);\n }\n }\n const numLen = numArr.length;\n const strLen = strArr.length;\n\n\tif (Math.abs(strLen - numLen) > 1) return \'\'\n\n\tfor(let i = 0; i < Math.min(numLen, strLen); i++) {\n str += `${numArr[i]}${strArr[i]}`;\n }\n \n if (numLen > strLen) {\n str += numArr[numLen - 1];\n } else if (strLen > numLen) {\n str = strArr[strLen - 1] + str;\n }\n \n return str;\n};\n``` | 3 | 0 | ['Array', 'JavaScript'] | 0 |
reformat-the-string | [Java] StringBuilder Solution | java-stringbuilder-solution-by-vinsinin-81pf | \nclass Solution {\n public String reformat(String s) {\n // StringBuilder for maintaining the characters\n\t\tStringBuilder sb = new StringBuilder(); | vinsinin | NORMAL | 2021-02-21T21:32:08.901162+00:00 | 2021-02-21T21:32:08.901204+00:00 | 735 | false | ```\nclass Solution {\n public String reformat(String s) {\n // StringBuilder for maintaining the characters\n\t\tStringBuilder sb = new StringBuilder();\n StringBuilder alpha = new StringBuilder();\n StringBuilder digit = new StringBuilder();\n \n\t\t// separate digits and alpha numerics\n for (char c : s.toCharArray()){\n if (Character.isDigit(c)) digit.append(c);\n else alpha.append(c);\n }\n \n\t\t// If any one of the builder length is greater than other then return empty\n if (Math.abs(alpha.length() - digit.length()) > 1) return "";\n \n int i = 0;\n int j = 0;\n //digit should be added first if its length is greater than alpha\n\t\tif (digit.length() > alpha.length()) sb.append(digit.charAt(j++));\n \n\t\t// if the complete string is not reached then add alpha and then digit, break when the length is >= to the string length\n while (sb.length() < s.length()){\n sb.append(alpha.charAt(i++));\n if (sb.length() >= s.length()) break;\n sb.append(digit.charAt(j++));\n }\n \n return sb.toString();\n }\n}\n``` | 3 | 0 | ['String', 'Java'] | 1 |
reformat-the-string | Python, filter based approach. FAST and simple. | python-filter-based-approach-fast-and-si-5qwn | \nclass Solution:\n def reformat(self, s: str) -> str:\n a1 = list(filter(str.isalpha, s))\n a2 = list(filter(str.isdigit, s))\n\n if ab | blue_sky5 | NORMAL | 2020-10-25T23:28:06.814114+00:00 | 2020-10-25T23:28:06.814157+00:00 | 506 | false | ```\nclass Solution:\n def reformat(self, s: str) -> str:\n a1 = list(filter(str.isalpha, s))\n a2 = list(filter(str.isdigit, s))\n\n if abs(len(a1) - len(a2)) > 1:\n return ""\n \n if len(a1) < len(a2): # ensure len(a1) >= len(a2)\n a1, a2 = a2, a1\n \n result = [c for t in zip(a1, a2) for c in t] + a1[len(a2):]\n \n return "".join(result)\n``` | 3 | 0 | ['Python', 'Python3'] | 1 |
reformat-the-string | Accepted Java - O(N) time and space | accepted-java-on-time-and-space-by-pd93-nvvs | \nclass Solution {\n public String reformat(String s) {\n \n // 1.) Separate chars and letters\n \n StringBuffer chars = new Stri | pd93 | NORMAL | 2020-04-19T04:24:36.462906+00:00 | 2020-04-20T01:37:28.323403+00:00 | 787 | false | ```\nclass Solution {\n public String reformat(String s) {\n \n // 1.) Separate chars and letters\n \n StringBuffer chars = new StringBuffer();\n StringBuffer letters = new StringBuffer(); \n for(Character c:s.toCharArray()){\n if(Character.isDigit(c)){\n letters.append(c);\n } else chars.append(c);\n }\n \n // 2.) Determine if we should start with char or letter (whichever is more in number)\n \n int charsL = chars.length();\n int lettersL =letters.length();\n String start, end;\n if(charsL>lettersL){\n start = new String(chars);\n end = new String(letters);\n } else {\n start = new String(letters);\n end = new String(chars);\n }\n \n // 3.) Just pick alternate, return "" if one is exhausted before it should\n \n int st = 0 ;\n int e = 0;\n boolean flag = false;\n StringBuffer res = new StringBuffer(); \n for(int i=0;i<charsL+lettersL;i++){\n if(flag==false){\n if(st>=start.length()) return "";\n res.append(start.charAt(st));\n st++;\n } else{\n if(e>=end.length()) return "";\n res.append(end.charAt(e));\n e++;\n }\n flag = !flag;\n }\n return new String(res);\n }\n}\n``` | 3 | 0 | ['Java'] | 2 |
reformat-the-string | Java | Clean Concise | O(N) time and O(N) space | java-clean-concise-on-time-and-on-space-cdtb0 | ```\n public String reformat(String s) {\n List digits = new ArrayList<>();\n List letters = new ArrayList<>();\n StringBuilder res = ne | ping_pong | NORMAL | 2020-04-19T04:04:44.143334+00:00 | 2020-04-19T04:04:44.143364+00:00 | 275 | false | ```\n public String reformat(String s) {\n List<Character> digits = new ArrayList<>();\n List<Character> letters = new ArrayList<>();\n StringBuilder res = new StringBuilder();\n char[] sChars = s.toCharArray();\n int n = sChars.length;\n for (char sChar : sChars) {\n if (Character.isDigit(sChar)) {\n digits.add(sChar);\n } else letters.add(sChar);\n }\n boolean pickDigit = digits.size() >= letters.size();\n for (int i = 0, l = 0, d = 0; i < n; i++) {\n if (pickDigit) {\n if (d == digits.size()) return "";\n res.append(digits.get(d++));\n } else {\n if (l == letters.size()) return "";\n res.append(letters.get(l++));\n }\n pickDigit = !pickDigit;\n }\n return res.toString();\n } | 3 | 2 | [] | 0 |
reformat-the-string | BEST solution using STACK ..Easy to unserstand with comments | best-solution-using-stack-easy-to-unsers-3ecr | 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 | ankurtiwari120196 | NORMAL | 2023-12-23T05:01:10.136285+00:00 | 2023-12-23T05:01:10.136304+00:00 | 383 | 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 reformat(String s) {\n if (s.length() == 1)\n return s;\n\n StringBuilder sb = new StringBuilder();\n Stack<Character> letters = new Stack();\n Stack<Character> digits = new Stack();\n\n for (char ch : s.toCharArray()) {\n if (Character.isLetter(ch)) {\n letters.push(ch);\n } else {\n digits.push(ch);\n }\n }\n\n if (Math.abs(digits.size() - letters.size()) > 1) //suppose stack1 size is 5 and second size is 4 then it will work eg covid (stack1) & 2019 (stack2) return 5-4=1 but greater than 1 return false\n return "";\n\n while (!letters.isEmpty() && !digits.isEmpty()) {\n sb.append(letters.pop()).append(digits.pop());\n }\n\n if (!letters.isEmpty())\n sb.append(letters.pop());\n else if (!digits.isEmpty())\n sb.insert(0, digits.pop());\n\n // return (s.length() == sb.toString().length()) ? sb.toString() : "";\n //no need of above line as last test case stack dcba & stack 21 will already be passed as 4-2=2 i.e greater than 1\n \n return sb.toString(); \n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
reformat-the-string | 100%beat,best approach to do this question in c++!! | 100beatbest-approach-to-do-this-question-il9v | 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 | Ashwin_Bharti | NORMAL | 2023-02-17T16:00:38.094707+00:00 | 2023-02-17T16:00:38.094752+00:00 | 698 | 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 reformat(string s) {\n stack<char>l,d;\n for (int i=0;i<s.size();i++){\n if(s[i]>=\'a\' && s[i]<=\'z\'){\n l.push(s[i]);\n }\n if(s[i]>=\'0\' && s[i]<=\'9\'){\n d.push(s[i]);\n } \n } \n\n if (l.size()==0 && d.size()==0){\n return "";\n }\n int n=(l.size()-d.size());\n if (abs(n)>=2){\n return "";\n }\n string p;\n if (l.size()>=d.size()){\n while(!l.empty()){\n p+=l.top();\n l.pop();\n if (!d.empty()){\n p+=d.top();\n d.pop();\n }\n }\n } \n if (d.size()>l.size()){\n while(!d.empty()){\n p+=d.top();\n d.pop();\n if (!l.empty()){\n p+=l.top();\n l.pop();\n }\n }\n } \n return p;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
reformat-the-string | Java || Two - Pointer | java-two-pointer-by-code_sanket-wo2d | \nclass Solution {\n public String reformat(String s) {\n StringBuilder alpha = new StringBuilder();\n StringBuilder digit = new StringBuilder( | code_sanket | NORMAL | 2023-01-11T07:58:24.536132+00:00 | 2023-01-11T07:58:24.536164+00:00 | 793 | false | ```\nclass Solution {\n public String reformat(String s) {\n StringBuilder alpha = new StringBuilder();\n StringBuilder digit = new StringBuilder();\n \n \n for(int i = 0 ; i < s.length() ; i++){\n char ch = s.charAt(i);\n if(ch >= \'0\' && ch <= \'9\'){\n digit.append(ch);\n }else{\n alpha.append(ch);\n }\n }\n \n if(Math.abs(digit.length() - alpha.length()) > 1)return "";\n \n StringBuilder ans = new StringBuilder();\n \n boolean flag = digit.length() >= alpha.length() ? true : false;\n \n int j = 0 , k = 0;\n \n for(int i = 0 ; i < s.length() ; i++){\n if(flag){\n ans.append(digit.charAt(j));\n j++;\n }else{\n ans.append(alpha.charAt(k));\n k++;\n }\n \n flag = !flag;\n }\n \n return ans.toString();\n }\n}\n``` | 2 | 0 | ['Two Pointers', 'String', 'Java'] | 0 |
reformat-the-string | C++ O(N) Time | O(1) space **Excluding answer | Two Pass | Counts and alternative Indexes | c-on-time-o1-space-excluding-answer-two-rs8ay | ```\nclass Solution {\npublic:\n \n string reformat(string s) {\n int digits{};\n int chars{};\n \n // count digits and spaces | cg1lc | NORMAL | 2022-08-13T06:24:16.445507+00:00 | 2022-08-13T06:25:50.560081+00:00 | 183 | false | ```\nclass Solution {\npublic:\n \n string reformat(string s) {\n int digits{};\n int chars{};\n \n // count digits and spaces\n for (auto ch : s)\n {\n if (ch >= \'a\' && ch <= \'z\') ++chars;\n else ++digits;\n }\n \n // If counts and digits differ by one they cannot be arranged as per req.\n if (abs(chars- digits) > 1) return "";\n \n\t\t// May be a better way to represent this..??\n string answer(s.size(), \' \');\n // If chars are more then first digit should be a char and digits between them\n int charIndex = chars > digits ? 0 : 1, digitIndex = !charIndex;\n for (auto ch : s)\n {\n if (ch >= \'a\' && ch <= \'z\') \n {\n answer[charIndex] = ch;\n charIndex += 2;\n }\n else\n {\n answer[digitIndex] = ch;\n digitIndex += 2;\n }\n }\n \n return answer;\n }\n \n}; | 2 | 0 | [] | 0 |
reformat-the-string | [Javascript] ALTERNATING Reformat using STACK | javascript-alternating-reformat-using-st-r2g3 | Intuition\n\nCollect all letter and digit first and count their number.\n\nIf diff(letter.len, digit.len)>1, just return "".\nOtherwise, we get 1 from BOTH arra | lynn19950915 | NORMAL | 2022-06-17T10:53:51.352412+00:00 | 2023-05-27T04:47:55.347262+00:00 | 256 | false | **Intuition**\n\nCollect all `letter` and `digit` first and count their number.\n\nIf `diff`(letter.len, digit.len)>1, just return `""`.\nOtherwise, we get 1 from BOTH array, and **always add letter first, then digit**.\n\n```\nL-D-L-D-...-L-D\n```\n\n> if there\'s a `letter` left, add it in the **END** -> `L-D-L-D-...-L-D`+L\n> if there\'s a `digit` left, add it in the **FRONT** -> D+`L-D-L-D-...-D-L`\n\n\n**Full-Codes**\n \n```\n# vers-1\nvar reformat = function(s) {\n let letter=[], digit=[];\n for(let i=0; i<s.length; i++){\n s[i]>=0 && s[i]<=9? digit.push(s[i]): letter.push(s[i]);\n }\n\t// impossible to reformat\n if(Math.abs(letter.length-digit.length)>=2){return ""}\n \n let i=0, output="";\n while(i<letter.length && i<digit.length){\n output=output+letter[i]+digit[i]; i++;\n }\n if(i<letter.length){output=output+letter[i]}; // add in the END\n if(i<digit.length){output=digit[i]+output}; // add in the FRONT\n return output;\n};\n```\n```\n# vers-2: Stack\nvar reformat = function(s) {\n let letter=[], digit=[];\n for(let i=0; i<s.length; i++){\n s[i]>=0 && s[i]<=9? digit.push(s[i]): letter.push(s[i]);\n }\n\t// impossible to reformat\n if(Math.abs(letter.length-digit.length)>=2){return ""}\n \n let output="";\n while(letter.length>0 && digit.length>0){\n output=letter.pop()+digit.pop();\n }\n return (digit.pop()||"")+output+(letter.pop()||"");\n};\n\n```\n\nThanks for your reading and **up-voting** :)\n\n**\u2B50 Check [HERE](https://github.com/Lynn19950915/LeetCode_King) for my full Leetcode Notes ~** | 2 | 0 | ['Stack', 'JavaScript'] | 0 |
reformat-the-string | Java O(1) space , O(N) time | java-o1-space-on-time-by-mesonny-9b9d | \n//2022/1/13 \u9019\u4E00\u984C\u4E0D\u7BA1\u600E\u6A23\u4E00\u5B9A\u8981\u5148\u5F97\u5230letters \u8DDF digits\u7684\u9577\u5EA6\n\nclass Solution {\n pub | mesonny | NORMAL | 2022-01-12T16:18:56.421295+00:00 | 2022-01-12T16:18:56.421330+00:00 | 147 | false | ```\n//2022/1/13 \u9019\u4E00\u984C\u4E0D\u7BA1\u600E\u6A23\u4E00\u5B9A\u8981\u5148\u5F97\u5230letters \u8DDF digits\u7684\u9577\u5EA6\n\nclass Solution {\n public String reformat(String s) {\n \n //prepare answer buffer\n int k = 0;\n char[] ans = new char[s.length()];\n \n //count #digits and #letters\n int letters = 0;\n int digits = 0;\n for(int i = 0; i < s.length(); i++) {\n if (Character.isDigit(s.charAt(i))) digits++;\n else letters++;\n }\n \n //return fast for not possible cases\n // you can easily figure it out \n if (Math.abs(letters - digits) > 1) return "";\n \n //if #letters > #digits, it must be copied first or else it won\'t fit into the answer array\n //and vice versa\n int digitIndex = 0, letterIndex = 1;\n if (letters > digits) {\n digitIndex = 1;\n letterIndex = 0;\n }\n \n //do copy\n for(int i = 0; i < s.length(); i++) {\n \n if (Character.isDigit(s.charAt(i))) {\n ans[digitIndex] = s.charAt(i); \n digitIndex += 2;\n }\n else {\n ans[letterIndex] = s.charAt(i); \n letterIndex += 2;\n }\n }\n \n \n \n return String.valueOf(ans);\n }\n}\n``` | 2 | 0 | [] | 1 |
reformat-the-string | Java solution | java-solution-by-humblef00l-jv1e | \nclass Solution {\n public String reformat(String s) {\n List<Character> digit = new ArrayList<>();\n List<Character> letter = new ArrayList<> | HUMBLEF00L | NORMAL | 2022-01-05T08:47:00.104041+00:00 | 2022-01-05T08:47:00.104093+00:00 | 68 | false | ```\nclass Solution {\n public String reformat(String s) {\n List<Character> digit = new ArrayList<>();\n List<Character> letter = new ArrayList<>();\n for(int i =0;i<s.length();i++)\n {\n char now = s.charAt(i);\n if(Character.isLetter(now)){\n letter.add(now);\n }\n else\n digit.add(now);\n }\n if(Math.abs(letter.size()-digit.size())>=2)return "";\n StringBuilder temp = new StringBuilder();\n boolean alternate = digit.size()>letter.size() ? true:false;\n for(int i=0;i<s.length();i++)\n {\n if(alternate){\n if(digit.size()!=0)\n {\n temp.append(digit.remove(0));\n }\n }else{\n if(letter.size()!=0)\n {\n temp.append(letter.remove(0));\n }\n }\n alternate = !alternate;\n }\n return temp.toString();\n }\n}\n``` | 2 | 0 | [] | 0 |
reformat-the-string | Simple java solution | simple-java-solution-by-siddhant_1602-jgew | class Solution {\n\n public String reformat(String s) {\n int i,c=0,m=0;\n String w="",d="";\n for(i=0;i=\'a\'&&s.charAt(i)<=\'z\')\n | Siddhant_1602 | NORMAL | 2021-08-01T16:44:25.698036+00:00 | 2022-03-08T06:23:03.503558+00:00 | 103 | false | class Solution {\n\n public String reformat(String s) {\n int i,c=0,m=0;\n String w="",d="";\n for(i=0;i<s.length();i++)\n {\n if(s.charAt(i)>=\'a\'&&s.charAt(i)<=\'z\')\n {\n c++;\n w=w+s.charAt(i);\n }\n else if(s.charAt(i)>=\'0\'&&s.charAt(i)<=\'9\')\n {\n m++;\n d=d+s.charAt(i);\n }\n }\n s="";\n if((c==m+1)||(c+1==m)||(c==m))\n {\n for(i=0;i<Math.min(m,c);i++)\n {\n s=s+w.charAt(i);\n s=s+d.charAt(i);\n }\n if(c>m)\n s=s+w.charAt(i);\n else if(c<m)\n s=d.charAt(i)+s;\n return s;\n }\n else\n return s;\n }\n} | 2 | 0 | [] | 0 |
reformat-the-string | Rust solution | rust-solution-by-bigmih-hyge | \nimpl Solution {\n pub fn reformat(s: String) -> String {\n let num_digits = s.chars().filter(|c| c.is_ascii_digit()).count() as i32;\n let nu | BigMih | NORMAL | 2021-07-09T16:43:07.266254+00:00 | 2021-07-09T16:43:07.266308+00:00 | 85 | false | ```\nimpl Solution {\n pub fn reformat(s: String) -> String {\n let num_digits = s.chars().filter(|c| c.is_ascii_digit()).count() as i32;\n let num_chars = s.len() as i32 - num_digits;\n\n if (num_digits - num_chars).abs() > 1 {\n return "".to_owned();\n }\n\n let mut res_vec = vec![\' \'; s.len()];\n let (mut ind_letter, mut ind_digit) = match num_chars >= num_digits {\n true => (0, 1),\n false => (1, 0),\n };\n\n for c in s.chars() {\n match c.is_ascii_digit() {\n true => {\n res_vec[ind_digit] = c;\n ind_digit += 2\n }\n false => {\n res_vec[ind_letter] = c;\n ind_letter += 2\n }\n }\n }\n res_vec.into_iter().collect()\n }\n}\n``` | 2 | 0 | ['Rust'] | 0 |
reformat-the-string | simple and basic | simple-and-basic-by-hrushee-kewb | \n\nclass Solution {\npublic:\n string reformat(string s) {\n string n="";\n string a="";\n for(auto i:s)\n {\n if(isd | Hrushee | NORMAL | 2021-06-14T18:37:14.361498+00:00 | 2021-06-14T18:37:14.361521+00:00 | 408 | false | \n```\nclass Solution {\npublic:\n string reformat(string s) {\n string n="";\n string a="";\n for(auto i:s)\n {\n if(isdigit(i))\n {\n n+=i;\n }\n else\n {\n a+=i;\n }\n }\n int i=n.size();\n int j=a.size();\n string ans="";\n if(abs(i-j)>1)\n {\n return ans;\n }\n if(i<j)\n {\n swap(n,a);\n }int z=min(i,j);int l=0;\n while(l<z)\n {\n ans+=n[l];\n ans+=a[l];l++;\n }\n if(abs(i-j)==1)\n {\n ans+=n[max(i,j)-1];\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C', 'C++'] | 0 |
reformat-the-string | [Java] Simple and Easy - EASY PEASY - O(N) - No Comments Needed | java-simple-and-easy-easy-peasy-on-no-co-s37x | \n\uD83D\uDC46\uD83D\uDC46UPVOTE IF YOU FIND THIS USEFUL\uD83D\uDC46\uD83D\uDC46\n\n\n\nclass Solution {\n public String reformat(String s) {\n int c | pulkitswami7 | NORMAL | 2020-09-14T05:32:11.481541+00:00 | 2020-09-14T05:32:11.481612+00:00 | 249 | false | <hr>\n\uD83D\uDC46\uD83D\uDC46UPVOTE IF YOU FIND THIS USEFUL\uD83D\uDC46\uD83D\uDC46\n<hr>\n\n```\nclass Solution {\n public String reformat(String s) {\n int c = 0, d = 0;\n for(char ch: s.toCharArray()){\n if(Character.isLetter(ch))\n c++;\n else\n d++;\n }\n \n if(c != d && c + 1 != d && c - 1 != d)\n return "";\n \n char ch[] = new char[c];\n char di[] = new char[d];\n \n for(int i = 0, j = 0, k = 0; i < s.length(); i++){\n if(Character.isLetter(s.charAt(i))){\n ch[j] = s.charAt(i);\n j++;\n }\n else{\n di[k] = s.charAt(i);\n k++;\n }\n }\n \n StringBuilder str = new StringBuilder();\n \n int len = Math.max(c, d);\n if(d > c){\n for(int i = 0; i < len; i++){\n if(i < d)\n str.append(di[i]);\n\n if(i < c)\n str.append(ch[i]);\n }\n }\n else{\n for(int i = 0; i < len; i++){\n if(i < c)\n str.append(ch[i]);\n\n if(i < d)\n str.append(di[i]);\n }\n }\n \n return str.toString();\n }\n}\n``` | 2 | 0 | [] | 0 |
reformat-the-string | Java 3ms StringBuilder | java-3ms-stringbuilder-by-sydneylin12-q0qm | \nclass Solution {\n public String reformat(String s) {\n if(s.length() == 1) return s;\n \n StringBuilder letters = new StringBuilder() | squidimenz | NORMAL | 2020-09-12T01:56:19.109863+00:00 | 2020-09-12T01:56:19.109925+00:00 | 201 | false | ```\nclass Solution {\n public String reformat(String s) {\n if(s.length() == 1) return s;\n \n StringBuilder letters = new StringBuilder();\n StringBuilder digits = new StringBuilder();\n \n for(int i = 0; i < s.length(); i++){\n if(Character.isDigit(s.charAt(i))){\n digits.append(s.charAt(i));\n }\n else{\n letters.append(s.charAt(i));\n }\n }\n \n if(digits.length() == 0 || letters.length() == 0) return "";\n \n StringBuilder res = new StringBuilder();\n int i = 0;\n int j = 0;\n \n while(i < letters.length() && j < digits.length()){\n res.append(letters.charAt(i));\n res.append(digits.charAt(j));\n i++;\n j++;\n }\n \n // One of the 2 SB\'s is empty\n if(i < letters.length()){\n res.append(letters.charAt(i));\n }\n \n if(j < digits.length()){\n res.insert(0, digits.charAt(i));\n j++;\n }\n \n return res.toString();\n }\n}\n``` | 2 | 0 | [] | 0 |
reformat-the-string | [PYTHON] Simple and Easy to understand | python-simple-and-easy-to-understand-by-gstff | \nclass Solution:\n def reformat(self, s: str) -> str:\n a=[]\n b=[]\n ans=\'\'\n for i in s:\n if i.isalpha():\n | het952 | NORMAL | 2020-06-24T05:31:09.438232+00:00 | 2020-06-24T05:31:09.438278+00:00 | 90 | false | ```\nclass Solution:\n def reformat(self, s: str) -> str:\n a=[]\n b=[]\n ans=\'\'\n for i in s:\n if i.isalpha():\n a.append(i)\n else:\n b.append(i)\n if abs(len(a)-len(b))<=1:\n while a and b:\n ans+=a.pop()\n ans+=b.pop()\n if a:\n ans+=a.pop()\n if b:\n ans=b.pop()+ans\n return ans\n \n``` | 2 | 0 | [] | 0 |
reformat-the-string | JavaScript easy understand | javascript-easy-understand-by-liangcode-acph | JavaScript Solution\n\n let letters = [];\n let digits = [];\n let res = \'\';\n \n for (let char of s) {\n if (\'a\' <= char && char <= \ | liangcode | NORMAL | 2020-04-30T20:55:26.494516+00:00 | 2020-04-30T20:56:35.344698+00:00 | 289 | false | JavaScript Solution\n\n let letters = [];\n let digits = [];\n let res = \'\';\n \n for (let char of s) {\n if (\'a\' <= char && char <= \'z\') {\n letters.push(char);\n } else {\n digits.push(char);\n }\n }\n let difference = letters.length - digits.length;\n if (difference >= 2 || difference <= -2) {\n return res;\n } else if (difference === -1) {\n letters = [\'\'].concat(letters);\n } else if (difference === 1) {\n digits = digits.concat([\'\']);\n }\n \n for (let i=0; i<letters.length; i++) {\n res += letters[i] + digits[i];\n }\n return res\n | 2 | 0 | ['JavaScript'] | 1 |
reformat-the-string | Easy to understand code | easy-to-understand-code-by-gh05t-8ubp | \nif(s == "")\n return "";\n\t\nint countW(0), countD(0);\nstring w, d;\nfor(const auto &c: s) {\n if(isdigit(c)) {\n countD++;\n d += c;\n | gh05t | NORMAL | 2020-04-20T00:46:21.155790+00:00 | 2020-04-20T03:09:30.125698+00:00 | 265 | false | ```\nif(s == "")\n return "";\n\t\nint countW(0), countD(0);\nstring w, d;\nfor(const auto &c: s) {\n if(isdigit(c)) {\n countD++;\n d += c;\n } else {\n countW++;\n w += c;\n }\n}\n\nif(abs(countW - countD) != 0 && abs(countW - countD) != 1)\n return "";\n\t\nstring ans(countW + countD, \' \');\nif(d.size() > w.size())\n swap(d, w);\nfor(int i = 0; i < s.size(); i += 2) {\n ans[i] = w.back();\n w.pop_back();\n}\nfor(int i = 1; i < s.size(); i += 2) {\n ans[i] = d.back();\n d.pop_back();\n}\nreturn ans;\n``` | 2 | 0 | ['C'] | 1 |
reformat-the-string | Java solution with comments | java-solution-with-comments-by-dhiren_72-bojk | Hope my solution helps\n\nclass Solution {\n public String reformat(String s) {\n ArrayList<Character> c = new ArrayList<>(); // to store character | dhiren_720 | NORMAL | 2020-04-19T05:32:06.671705+00:00 | 2020-04-19T05:32:06.671775+00:00 | 186 | false | Hope my solution helps\n```\nclass Solution {\n public String reformat(String s) {\n ArrayList<Character> c = new ArrayList<>(); // to store character like a,b,c\n ArrayList<Character> n = new ArrayList<>(); // to store digits like 1,2,3\n for(int i=0;i<s.length();i++){\n char c1 = s.charAt(i);\n if(c1>=\'0\' && c1<=\'9\'){\n n.add(c1);\n }\n else{\n c.add(c1);\n }\n }\n if(Math.abs(c.size()-n.size()) > 1){ \n return "";\n }\n StringBuilder sb = new StringBuilder();\n int i1=0;\n int i2=0;\n int f=0;\n if(n.size()>c.size()){ // if digits are one more than character than first put digit\n sb.append(n.get(i2));\n i2++;\n }\n while(i1<c.size() && i2<n.size()){ // now alternatively put digit and character in string\n int p = (f%2);\n if(p==0){\n sb.append(c.get(i1));\n i1++;\n }\n else{\n sb.append(n.get(i2));\n i2++;\n }\n f++;\n }\n if(i1<c.size()){\n sb.append(c.get(i1));\n }\n if(i2<n.size()){\n sb.append(n.get(i2));\n }\n return sb.toString();\n }\n}\n```\nHope u liked my post and don\'t forget to upvote!!! | 2 | 1 | [] | 0 |
reformat-the-string | Python Solution using zip_longest() | python-solution-using-zip_longest-by-cpp-vu8q | \nfrom itertools import zip_longest\n\nclass Solution: \n def reformat(self, s: str) -> str:\n if len(s) == 1:\n return s\n\t\t\t\n\t\t# I | cppygod | NORMAL | 2020-04-19T04:11:32.015238+00:00 | 2020-04-19T04:17:15.550917+00:00 | 254 | false | ```\nfrom itertools import zip_longest\n\nclass Solution: \n def reformat(self, s: str) -> str:\n if len(s) == 1:\n return s\n\t\t\t\n\t\t# If the input string contains only digits (or) only letters\n if s.isalpha() or s.isdigit():\n return ""\n \n\t\t# Getting the numbers & letters seperately\n numbers = [c for c in s if c.isdigit()]\n letters = [c for c in s if c.isalpha()]\n \n res = ""\n \n\t\t# Deciding when to start with letters, and when to start with numbers\n if len(letters) > len(numbers):\n for c in zip_longest(letters, numbers):\n c = list(c)\n c = [str(i or \'\') for i in c] # Getting rid of None type\n res += \'\'.join(f for f in c)\n return res\n\n else:\n for c in zip_longest(numbers, letters):\n c = list(c)\n c = [str(i or \'\') for i in c] # Getting rid of None type\n res += \'\'.join(f for f in c)\n return res\n``` | 2 | 1 | ['Python', 'Python3'] | 0 |
reformat-the-string | C++ simple O(n) solution | c-simple-on-solution-by-sanyamg99-xlb7 | \nclass Solution {\npublic:\n string reformat(string s) {\n string a="",b="";\n for(int i=0;i<s.length();i++){\n if(isdigit(s[i])) b | sanyamg99 | NORMAL | 2020-04-19T04:03:38.109687+00:00 | 2020-04-19T04:03:38.109740+00:00 | 173 | false | ```\nclass Solution {\npublic:\n string reformat(string s) {\n string a="",b="";\n for(int i=0;i<s.length();i++){\n if(isdigit(s[i])) b+=s[i];\n else a+=s[i];\n }\n if(a=="" && b.length()==1) return b;\n else if(b=="" && a.length()==1) return a;\n else if(a=="" || b=="") return "";\n string ans="";\n if(a.length()>b.length()){\n for(int i=0;i<a.length();i++){\n ans+=a[i];\n if(i<b.length())\n ans+=b[i];\n }\n }else{\n for(int i=0;i<b.length();i++){\n ans+=b[i];\n if(i<a.length())\n ans+=a[i];\n }\n }\n return ans;\n }\n};\n``` | 2 | 1 | [] | 0 |
reformat-the-string | [C++] Interpolating two arrays | c-interpolating-two-arrays-by-zhanghuime-d54a | Given an array containing lowercase letters and digits, return a new array interpolating letters and digits.\n\n# Explanation\n\nThe difference between the numb | zhanghuimeng | NORMAL | 2020-04-19T04:01:22.806967+00:00 | 2020-04-19T04:01:22.807024+00:00 | 627 | false | Given an array containing lowercase letters and digits, return a new array interpolating letters and digits.\n\n# Explanation\n\nThe difference between the number of letters and digits must be <= 1. Just interpolate the one with bigger size first.\n\nThe time complexity is O(n).\n\n# C++ Solution\n\n```cpp\nclass Solution {\npublic:\n string reformat(string s) {\n vector<char> digits, alpha;\n for (char c: s) {\n if (\'a\' <= c && c <= \'z\')\n alpha.push_back(c);\n else\n digits.push_back(c);\n }\n \n if (abs((int) digits.size() - (int) alpha.size()) > 1) return "";\n if (alpha.size() > digits.size()) swap(digits, alpha);\n int i = 0, j = 0;\n string ans;\n while (i < digits.size() || j < alpha.size()) {\n if (i < digits.size()) {\n ans += digits[i];\n i++;\n }\n if (j < alpha.size()) {\n ans += alpha[j];\n j++;\n }\n }\n return ans;\n }\n};\n```\n | 2 | 1 | [] | 0 |
reformat-the-string | Solution Palindrome do Lucas Marcao - slow. | solution-palindrome-do-lucas-marcao-slow-9txo | IntuitionMinha primeira ideia para resolver esse problema foi garantir que a string resultante alternasse entre letras e números. Eu sabia que, para isso, seria | marcaozitos | NORMAL | 2025-03-28T16:14:20.042359+00:00 | 2025-03-28T16:14:20.042359+00:00 | 33 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Minha primeira ideia para resolver esse problema foi garantir que a string resultante alternasse entre letras e números. Eu sabia que, para isso, seria necessário contar a quantidade de letras e números na string de entrada e verificar se a diferença entre eles era aceitável para permitir a alternância. Caso essa diferença fosse muito grande, seria impossível intercalar os caracteres de maneira correta, e a função deveria retornar uma string vazia.
# Approach
<!-- Describe your approach to solving the problem. -->
A abordagem foi organizar a solução da seguinte forma:
1- Contagem de letras e números: Primeiramente, percorri a string de entrada, identificando e separando as letras e números. Para isso, usei dois vetores (vazioLetra e vazioNum) para armazenar respectivamente as letras e números encontrados. Além disso, utilizei dois contadores para acompanhar quantas letras e números a string possui.
2- Verificação de viabilidade: Após contar as letras e números, a verificação foi realizada para garantir que a diferença entre a quantidade de letras e números não fosse superior a 1. Caso essa diferença fosse maior, seria impossível intercalar os caracteres e retornaria uma string vazia.
3- Alternância entre letras e números: Com base na quantidade de letras e números, decidi qual tipo de caractere deveria começar (letra ou número) e usei dois índices para percorrer os vetores de letras e números, alternando entre eles para formar a string final.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n) A complexidade do tempo é linear, pois a string de entrada é percorrida uma vez para contar e separar os caracteres, e a montagem da string final também envolve um único loop que percorre os caracteres intercalados.
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(n) A complexidade de espaço é linear, pois usamos dois vetores adicionais para armazenar as letras e números separados da string de entrada, além das variáveis auxiliares. O tamanho total dos vetores será proporcional ao tamanho da string de entrada.
# Code
```cpp []
class Solution {
public:
string reformat(string s) {
vector<string> numeros = {"0", "1", "2", "3", "4",
"5", "6", "7", "8", "9"};
unsigned int contaLetras = 0;
unsigned int contaNumeros = 0;
vector<string> letras = {"a", "b", "c", "d", "e", "f", "g", "h", "i",
"j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "x", "y", "w", "z"};
vector<string> vazioLetra = {};
vector<string> vazioNum = {};
for (unsigned int i = 0; i < s.size(); i++) {
for (unsigned int j = 0; j < numeros.size(); j++) {
if (s[i] == numeros[j][0]) {
contaNumeros = contaNumeros + 1;
vazioNum.push_back(numeros[j]);
}
}
for (unsigned int k = 0; k < letras.size(); k++) {
if (s[i] == letras[k][0]) {
contaLetras = contaLetras + 1;
vazioLetra.push_back(letras[k]);
}
}
}
if (((vazioNum.size() + 1) < vazioLetra.size()) or
((vazioLetra.size() + 1) < vazioNum.size())) {
string nada = "";
return nada;
}
string finalmente = "";
int cont = 2;
int contLetra = 0;
int contNum = 0;
if (vazioNum.size() > vazioLetra.size()) {
cont = 1;
}
int tamanhoFinalmente = (vazioNum.size() + vazioLetra.size());
if (cont == 2) {
for (unsigned int i = 0; i < tamanhoFinalmente; i++) {
if (i % 2 == 0) {
finalmente = finalmente + vazioLetra[contLetra][0];
contLetra++;
} else {
finalmente = finalmente + vazioNum[contNum][0];
contNum++;
}
}
}
if (cont == 1) {
for (unsigned int i = 0; i < tamanhoFinalmente; i++) {
if (i % 2 == 0) {
finalmente = finalmente + vazioNum[contNum][0];
contNum++;
} else {
finalmente = finalmente + vazioLetra[contLetra][0];
contLetra++;
}
}
}
// finalmente "X0X0X0";
return finalmente;
}
};
``` | 1 | 0 | ['Array', 'Math', 'String', 'C++'] | 1 |
reformat-the-string | Code is lengthy but logic is very simple | please upvote | code-is-lengthy-but-logic-is-very-simple-5rh7 | \n\n# Code\njava []\nclass Solution {\n public String reformat(String s) {\n StringBuilder l=new StringBuilder();\n StringBuilder d=new StringB | Lil_kidZ | NORMAL | 2024-09-19T23:34:14.466731+00:00 | 2024-09-19T23:34:14.466759+00:00 | 242 | false | \n\n# Code\n```java []\nclass Solution {\n public String reformat(String s) {\n StringBuilder l=new StringBuilder();\n StringBuilder d=new StringBuilder();\n StringBuilder ans=new StringBuilder();\n for(int i=0;i<s.length();i++){\n if(Character.isLetter(s.charAt(i))){\n l.append(s.charAt(i));\n }else d.append(s.charAt(i));\n }\n if(Math.abs(l.length()-d.length())>1){\n return "";\n }\n if(l.length()>d.length()){\n for(int i=0;i<d.length();i++){\n ans.append(l.charAt(i));\n ans.append(d.charAt(i));\n }\n ans.append(l.charAt(l.length()-1));\n }\n if(d.length()>l.length()){\n for(int i=0;i<l.length();i++){\n ans.append(d.charAt(i));\n ans.append(l.charAt(i));\n }\n ans.append(d.charAt(d.length()-1));\n }\n if(d.length()==l.length()){\n for(int i=0;i<d.length();i++){\n ans.append(d.charAt(i));\n ans.append(l.charAt(i));\n } \n }\n return ans.toString();\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
reformat-the-string | bahut saare cases handle krne pade need to optimize it a lot hum bhi kr lenge :D | bahut-saare-cases-handle-krne-pade-need-l9qwa | 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 | yesyesem | NORMAL | 2024-09-09T18:42:36.303066+00:00 | 2024-09-09T18:42:36.303100+00:00 | 69 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string reformat(string s) {\n string num;\n string alpha;\n string ans;\n if(s.length()==1)\n return s;\n\n for(int i=0;i<s.length();i++)\n {\n if(isalpha(s[i]))\n alpha.push_back(s[i]);\n else\n num.push_back(s[i]);\n }\n \n int y = abs(static_cast<int>(alpha.length()) - static_cast<int>(num.length()));\n\n if(y>=2)\n return ans;\n\n if(num.length()==0||alpha.length()==0)\n return ans;\n\n int k=0;\n int l=0;\n\n bool p=false;\n\n\n if(alpha.length()>num.length())\n {\n p=true;\n }\n \n\n\n\n for(int i=0;i<min(alpha.length(),num.length());i++)\n {\n if(p==true)\n {\n ans.push_back(alpha[l++]);\n ans.push_back(num[k++]);\n\n }\n else\n { ans.push_back(num[k++]);\n ans.push_back(alpha[l++]);}\n }\n if(alpha.length()==num.length())\n return ans;\n\n\n if(p==true)\n {\n ans.push_back(alpha[l]);\n }\n else\n {\n ans.push_back(num[k]);\n }\n \n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
reformat-the-string | 45 MS | IT IS SIMPLE FOR YOU | 45-ms-it-is-simple-for-you-by-justchis10-6ggc | \n\n# CODE\n\nclass Solution:\n def reformat(self, s: str) -> str:\n ls = list(s)\n digits = list(filter(lambda x : x.isdigit(), list(s)))\n | JustChis100 | NORMAL | 2024-03-29T16:50:00.165664+00:00 | 2024-03-29T16:50:00.165694+00:00 | 208 | false | \n\n# CODE\n```\nclass Solution:\n def reformat(self, s: str) -> str:\n ls = list(s)\n digits = list(filter(lambda x : x.isdigit(), list(s)))\n letters = list(filter(lambda x : not x.isdigit(), list(s)))\n cd = len(digits)\n cl = len(letters)\n res = ""\n if abs(cd - cl) < 2 :\n for i in range(min(cd, cl)) :\n if cd > cl :\n res += digits.pop() + letters.pop()\n else :\n res += letters.pop() + digits.pop() \n if digits :\n res += digits.pop() \n if letters :\n res += letters.pop() \n return res\n return ""\n```\n## PLS> | 1 | 0 | ['String', 'Python', 'Python3'] | 1 |
reformat-the-string | Easy method for beginners O(n) | easy-method-for-beginners-on-by-arun_bal-7ia6 | 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 | arun_balakrishnan | NORMAL | 2024-03-20T17:21:21.668499+00:00 | 2024-03-20T17:21:21.668531+00:00 | 353 | 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 reformat(self, s: str) -> str:\n letters = [i for i in s if i.isalpha()]\n digits = [i for i in s if i.isdigit()]\n l = len(letters)\n d = len(digits)\n ans = ""\n exist = [-1, 0, 1]\n if (l-d) not in exist:\n return ans\n elif l > d:\n for i in range(l):\n if i != l-1:\n ans += letters[i] + digits[i]\n else:\n ans += letters[i]\n elif l == d:\n for i in range(l):\n ans += letters[i] + digits[i]\n else:\n for i in range(d):\n if i != d-1:\n ans += digits[i] + letters[i]\n else:\n ans += digits[i]\n return ans\n\n \n``` | 1 | 0 | ['Python3'] | 0 |
reformat-the-string | Easy 3ms java solution, beats 94.21% | easy-3ms-java-solution-beats-9421-by-ari-r06j | 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 | arijeet7 | NORMAL | 2024-02-26T15:10:11.876841+00:00 | 2024-02-26T15:10:11.876878+00:00 | 383 | 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 reformat(String s) {\n int n = s.length();\n char[] digits = new char[n];\n char[] alpha = new char[n];\n int alphaIndex = 0;\n int digitsIndex = 0;\n \n for (int i = 0; i < n; i++) {\n if (Character.isDigit(s.charAt(i))) {\n digits[digitsIndex++] = s.charAt(i);\n } else {\n alpha[alphaIndex++] = s.charAt(i);\n }\n }\n \n if (Math.abs(digitsIndex - alphaIndex) > 1) {\n return "";\n }\n \n StringBuilder resultBuilder = new StringBuilder();\n \n if (digitsIndex >= alphaIndex) {\n for (int i = 0; i < alphaIndex; i++) {\n resultBuilder.append(digits[i]);\n resultBuilder.append(alpha[i]);\n }\n if (digitsIndex > alphaIndex) {\n resultBuilder.append(digits[digitsIndex - 1]);\n }\n } else {\n for (int i = 0; i < digitsIndex; i++) {\n resultBuilder.append(alpha[i]);\n resultBuilder.append(digits[i]);\n }\n resultBuilder.append(alpha[alphaIndex - 1]);\n }\n \n return resultBuilder.toString();\n }\n}\n\n``` | 1 | 0 | ['Java'] | 1 |
reformat-the-string | [ANSI C] Brute force | ansi-c-brute-force-by-pbelskiy-s9bi | c\n#define MAX_CHARS 500\n\nchar *reformat(char *s)\n{\n int l = 0, n = 0;\n\n char *letters = malloc(MAX_CHARS);\n char *numbers = malloc(MAX_CHARS);\ | pbelskiy | NORMAL | 2023-09-12T14:00:30.769503+00:00 | 2023-09-12T14:00:30.769526+00:00 | 65 | false | ```c\n#define MAX_CHARS 500\n\nchar *reformat(char *s)\n{\n int l = 0, n = 0;\n\n char *letters = malloc(MAX_CHARS);\n char *numbers = malloc(MAX_CHARS);\n\n for (int i = 0 ; i < strlen(s) ; i++) {\n if (s[i] >= \'a\') {\n letters[l++] = s[i];\n } else {\n numbers[n++] = s[i];\n }\n }\n\n if (l - n > 1 || n - l > 1)\n return "";\n\n char *string = calloc(l + n + 1 + 100, 1);\n int i = 0, j = 0, k = 0;\n\n if (l >= n) {\n while (i < strlen(s)) {\n if (j < l)\n string[i++] = letters[j++];\n if (k < n)\n string[i++] = numbers[k++];\n }\n } else if (n > l) {\n while (i < strlen(s)) {\n if (k < n)\n string[i++] = numbers[k++];\n if (j < l)\n string[i++] = letters[j++];\n }\n }\n\n return string;\n}\n``` | 1 | 0 | ['C'] | 0 |
reformat-the-string | C++ easy/simple Solution || Best Sol || easy to Understand || simple Approach | c-easysimple-solution-best-sol-easy-to-u-u57n | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n## c++ simple Solution | sanjiv0286 | NORMAL | 2023-07-01T06:53:24.751288+00:00 | 2023-07-01T06:53:24.751312+00:00 | 28 | 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## c++ simple Solution easy to understand\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#include<bits/stdc++.h>\nclass Solution {\npublic:\n string reformat(string s) {\n vector<int>l;\n vector<int>d;\n string res = "";\n int a=0,b=0;\n for(int i=0;i<s.size();i++){\n if(isalpha(s[i])){\n l.push_back(s[i]);\n }\n else{\n d.push_back(s[i]);\n }\n }\n sort(l.begin(),l.end());\n sort(d.begin(),d.end());\n // if(l.size()==s.size()){\n // return "";\n // }\n // if(d.size()==s.size()){\n // return "";\n // }\n if (abs((int)l.size() - (int)d.size()) > 1) {\n return "";\n }\n\n if (l.size() > d.size()) {\n std::swap(l, d);\n }\n while(a < l.size() && b<d.size()){\n res += d[b++];\n res += l[a++];\n }\n if (b < d.size()) {\n res += d[b++];\n }\n\n return res;\n }\n};\n | 1 | 0 | ['C++'] | 1 |
reformat-the-string | [Python3] - One-Pass - No Space other than Solution | python3-one-pass-no-space-other-than-sol-7mg9 | Intuition\n Describe your first thoughts on how to solve this problem. \nWe make an array which is one larger than our input string and put digits at every even | Lucew | NORMAL | 2022-10-26T21:00:25.774723+00:00 | 2022-10-26T21:00:25.774766+00:00 | 86 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe make an array which is one larger than our input string and put digits at every even and characters at every odd position.\n\nWhile doing that we increase pointers for both of those. Once these pointers are out of scope, we have too many digits/characters.\n\nWe need to take care of the special case, like covid2019:\nOur solution would be [2,c,0,o,1,v,9,i,,d] since we have one more character than digits, but our digits start at 0 (allowed to have one more).\n\nIn this special case we take the two from the start and place it between the second last and last, allowing one more character than digit.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing a pre-initialized list, we do not use any extra space other than solution space and only need a single pass.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1) if we neglect solution space.\n# Code\n```\nclass Solution:\n def reformat(self, s: str) -> str:\n\n # make a solution\n n = len(s)\n sol = [""]*(n+1)\n nr_pointer = 0\n chr_pointer = 1\n for char in s:\n if char.isdigit():\n if nr_pointer >= n:\n return ""\n sol[nr_pointer] = char\n nr_pointer += 2\n else:\n if chr_pointer >= n+1:\n return ""\n sol[chr_pointer] = char\n chr_pointer += 2\n \n # check the char pointer (whether there were)\n if chr_pointer == n+2:\n sol[-2] = sol[0]\n sol[0] = ""\n \n return "".join(sol)\n``` | 1 | 0 | ['Python3'] | 0 |
reformat-the-string | C++ | STL | O(N) | SPACE(N) | c-stl-on-spacen-by-nmashtalirov-0ojh | Algorithm:\n\n1. Divide the source string into letters and numbers using the standard std::stable_partition function.\n\n2. Check that the number of letters and | nmashtalirov | NORMAL | 2022-09-22T15:11:57.482017+00:00 | 2022-09-22T15:11:57.482066+00:00 | 74 | false | **Algorithm:**\n\n1. Divide the source string into letters and numbers using the standard std::stable_partition function.\n\n2. Check that the number of letters and numbers differs by no more than 1 modulo, otherwise return an empty string.\n\n3. If there are more letters the numbers, add the first letter to the formatted string and moves the iterator to the next one.\n\n4. Go through a source string and add a number and a letter alternately.\n\n5. Return the formatted string.\n\n```\nstd::string reformat(std::string source)\n{\n\tauto digit{std::stable_partition(std::begin(source),\n\t\t\t\t\t\t\t\t\t std::end(source),\n\t\t\t\t\t\t\t\t\t ::isalpha)};\n\n\tauto difference{std::distance(std::begin(source), digit) -\n\t\t\t\t\tstd::distance(digit, std::end(source))};\n\n\tif (std::abs(difference) > 1)\n\t{\n\t\treturn {};\n\t}\n\n\tstd::string formatted;\n\tauto letter{std::begin(source)};\n\tif (difference > 0)\n\t{\n\t\tformatted.push_back(*std::begin(source));\n\t\tletter = std::next(std::begin(source));\n\t}\n\n\tfor (auto separator{digit}; letter < separator ||\n\t\t\t\t\t\t\t\tdigit < std::end(source);\n\t\t ++letter, ++digit)\n\t{\n\t\tif (digit < std::end(source))\n\t\t{\n\t\t\tformatted.push_back(*digit);\n\t\t}\n\t\tif (letter < separator)\n\t\t{\n\t\t\tformatted.push_back(*letter);\n\t\t}\n\t}\n\n\treturn formatted;\n}\n``` | 1 | 0 | ['C', 'C++'] | 0 |
reformat-the-string | C# | c-by-neildeng0705-h1vf | \npublic class Solution {\n public string Reformat(string s) \n { \n char[] digits = s.ToCharArray().Where(x => Char.IsDigit(x)).ToArray();\n | neildeng0705 | NORMAL | 2022-08-13T15:06:43.831106+00:00 | 2022-08-13T15:06:43.831149+00:00 | 130 | false | ```\npublic class Solution {\n public string Reformat(string s) \n { \n char[] digits = s.ToCharArray().Where(x => Char.IsDigit(x)).ToArray();\n char[] chars = s.ToCharArray().Where(x => !Char.IsDigit(x)).ToArray();\n\n if (Math.Abs(digits.Length-chars.Length) > 1)\n {\n return string.Empty;\n }\n\n if (digits.Length < chars.Length)\n {\n var temp = chars.Zip(digits).SelectMany(tuple => new[] { tuple.First, tuple.Second });\n return string.Join("", temp) + chars[chars.Length -1];\n }\n else if (digits.Length == chars.Length)\n {\n var temp = digits.Zip(chars).SelectMany(tuple => new[] { tuple.First, tuple.Second });\n return string.Join("", temp);\n }\n else\n {\n var temp = digits.Zip(chars).SelectMany(tuple => new[] { tuple.First, tuple.Second });\n return string.Join("", temp) + digits[digits.Length - 1];\n }\n }\n}\n``` | 1 | 0 | [] | 0 |
reformat-the-string | Java O(n) Runtime better than 97% Space better than 96% | java-on-runtime-better-than-97-space-bet-l1wf | \nclass Solution {\n public String reformat(String s) {\n int letters = 0, numbers = 0;\n for(char c : s.toCharArray()){\n if(Charac | anonymousLCer | NORMAL | 2022-07-22T17:36:51.364756+00:00 | 2022-07-22T17:36:51.364791+00:00 | 208 | false | ```\nclass Solution {\n public String reformat(String s) {\n int letters = 0, numbers = 0;\n for(char c : s.toCharArray()){\n if(Character.isDigit(c)) numbers++;\n else letters++;\n }\n \n if(Math.abs(letters - numbers) > 1) return "";\n return letters > numbers ? makeResult(s,0,1,true) : makeResult(s,1,0,false);\n }\n \n private String makeResult(String s, int i, int j, boolean flag){\n char[] c = s.toCharArray();\n char[] res = new char[s.length()];\n for(char ch: c){\n if(Character.isLetter(ch)){\n res[i] = ch;\n i+=2;\n }else{\n res[j] = ch;\n j+=2;\n }\n }\n return String.valueOf(res);\n }\n}\n``` | 1 | 0 | [] | 0 |
reformat-the-string | Python | Easy Solution | python-easy-solution-by-aryonbe-4rld | ```\nclass Solution:\n def reformat(self, s: str) -> str:\n alphabets = []\n numerics = []\n for c in s:\n if c.isnumeric():\ | aryonbe | NORMAL | 2022-07-17T22:20:22.989420+00:00 | 2022-07-17T22:20:22.989451+00:00 | 325 | false | ```\nclass Solution:\n def reformat(self, s: str) -> str:\n alphabets = []\n numerics = []\n for c in s:\n if c.isnumeric():\n numerics.append(c)\n else:\n alphabets.append(c)\n if abs(len(alphabets) - len(numerics)) > 1: return ""\n res = []\n while alphabets or numerics:\n if len(alphabets) >= len(numerics):\n if alphabets:\n res.append(alphabets.pop())\n if numerics:\n res.append(numerics.pop())\n else:\n if numerics:\n res.append(numerics.pop())\n if alphabets:\n res.append(alphabets.pop())\n return "".join(res)\n | 1 | 0 | ['Python'] | 0 |
reformat-the-string | c++ | easy | basic | c-easy-basic-by-srv-er-en9v | \nclass Solution {\npublic:\n string reformat(string s) {\n string dg,al;\n for(auto&i:s)isdigit(i)?dg+=i:al+=i;\n if(abs((int)size(dg)- | srv-er | NORMAL | 2022-07-05T01:14:43.430017+00:00 | 2022-07-05T01:14:43.430062+00:00 | 337 | false | ```\nclass Solution {\npublic:\n string reformat(string s) {\n string dg,al;\n for(auto&i:s)isdigit(i)?dg+=i:al+=i;\n if(abs((int)size(dg)-(int)size(al))>1) return "";\n int i=0,j=0,k=0;\n string ans(size(s),\' \');\n bool cdg=size(dg)>size(al);\n while(k<size(s)){\n if(cdg)ans[k++]=dg[i++];\n else ans[k++]=al[j++];\n cdg=!cdg;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
reformat-the-string | O(n) time, O(n) space, concise, stack | on-time-on-space-concise-stack-by-yayaro-9n6w | \npublic class Solution {\n public string Reformat(string s) {\n var digits = new Stack<char>(s.Where(c => \'0\' <= c && c <= \'9\'));\n var le | yayarokya | NORMAL | 2022-04-21T12:44:47.084153+00:00 | 2022-04-21T12:50:51.154193+00:00 | 64 | false | ```\npublic class Solution {\n public string Reformat(string s) {\n var digits = new Stack<char>(s.Where(c => \'0\' <= c && c <= \'9\'));\n var letters = new Stack<char>(s.Where(c => c < \'0\' || \'9\' < c));\n if(1 < Math.Abs(digits.Count - letters.Count)) {\n return "";\n }\n var sb = new StringBuilder();\n var stack = letters.Count < digits.Count ? digits : letters;\n while(stack.Any()) {\n sb.Append(stack.Pop());\n stack = stack == letters ? digits : letters;\n }\n return sb.ToString();\n }\n}\n``` | 1 | 0 | ['Stack'] | 0 |
reformat-the-string | Python3 Solution | python3-solution-by-hgalytoby-6lzh | python\nclass Solution:\n def reformat(self, s: str) -> str:\n nums, chars = [], []\n [(chars, nums)[char.isdigit()].append(str(char)) for char | hgalytoby | NORMAL | 2022-03-19T14:27:43.739450+00:00 | 2022-03-19T14:40:03.113228+00:00 | 134 | false | ```python\nclass Solution:\n def reformat(self, s: str) -> str:\n nums, chars = [], []\n [(chars, nums)[char.isdigit()].append(str(char)) for char in s]\n nums_len, chars_len = len(nums), len(chars)\n if 2 > nums_len - chars_len > -2:\n a, b = ((chars, nums), (nums, chars))[nums_len > chars_len]\n return reduce(lambda x, y: x + y[0] + y[1], itertools.zip_longest(a, b, fillvalue=\'\'), \'\')\n return \'\'\n``` | 1 | 0 | ['Python3'] | 0 |
reformat-the-string | Python solution with no extra space | python-solution-with-no-extra-space-by-l-dt8z | \nclass Solution:\n def reformat(self, s: str) -> str:\n count_alpha = 0\n count_digit = 0\n \n for i in s:\n \n | lazarus29 | NORMAL | 2022-03-02T21:03:43.658570+00:00 | 2022-03-02T21:03:43.658601+00:00 | 74 | false | ```\nclass Solution:\n def reformat(self, s: str) -> str:\n count_alpha = 0\n count_digit = 0\n \n for i in s:\n \n if i.isalpha():\n count_alpha += 1\n else:\n count_digit += 1\n \n if abs(count_alpha - count_digit) > 1:\n return ""\n \n i = 0\n j = 0\n answer = ""\n \n while len(answer) < len(s):\n \n while i < len(s) and not s[i].isalpha():\n i += 1\n\n while j < len(s) and s[j].isalpha():\n j += 1\n \n if i < len(s) and j < len(s):\n answer += (s[i] + s[j]) if count_alpha > count_digit else (s[j] + s[i])\n \n elif i < len(s):\n answer += s[i]\n \n elif j < len(s):\n answer += s[j]\n \n i += 1\n j += 1\n \n return answer\n``` | 1 | 0 | [] | 0 |
reformat-the-string | C++ | CPP | 100% FASTER | 80% SPACE | SIMPLE SOLUTION | c-cpp-100-faster-80-space-simple-solutio-muci | \nclass Solution {\npublic:\n string reformat(string s) {\n int n = s.size();\n string ans,digits,chars;\n for(int i = 0;i<n;i++){\n | UnknownOffline | NORMAL | 2022-02-11T06:10:52.732075+00:00 | 2022-02-11T06:10:52.732100+00:00 | 251 | false | ```\nclass Solution {\npublic:\n string reformat(string s) {\n int n = s.size();\n string ans,digits,chars;\n for(int i = 0;i<n;i++){\n if(s[i] >= \'0\' && s[i] <= \'9\') digits += s[i];\n else chars += s[i];\n }\n int i = 0, j = 0;\n int diff = digits.size() - chars.size();\n if(abs(diff) > 1 )\n return ans;\n else if(digits.size() > chars.size())\n ans += digits[i++];\n else if(digits.size() < chars.size())\n ans += chars[j++];\n for(;i < digits.size();i++,j++){\n if(i > j){\n ans += chars[j];\n ans += digits[i];\n }\n else{\n ans += digits[i];\n ans += chars[j];\n }\n }\n return ans;\n }\n \n};\n```\n\n | 1 | 0 | ['C', 'C++'] | 0 |
reformat-the-string | Simple C++ Solution | simple-c-solution-by-trishit-pal-4nhi | \tstring reformat(string s) {\n vector s1,s2;\n for(int i=0;i1)\n return "";\n int i=0,j=0;\n string ans="";\n if( | trishit-pal | NORMAL | 2022-01-05T09:04:04.963893+00:00 | 2022-01-05T09:04:04.963932+00:00 | 214 | false | \tstring reformat(string s) {\n vector<char> s1,s2;\n for(int i=0;i<s.size();i++)\n {\n if(isalpha(s[i]))\n s1.push_back(s[i]);\n else\n s2.push_back(s[i]);\n }\n int n=s1.size(), m=s2.size();\n if(abs(n-m)>1)\n return "";\n int i=0,j=0;\n string ans="";\n if(s1.size()>s2.size()){\n while(i<s1.size() && j<s2.size())\n {\n ans+=s1[i];\n ans+=s2[j];\n i++;j++;\n }\n ans+=s1[i];\n }\n else\n {\n while(i<s1.size() && j<s2.size())\n {\n ans+=s2[j];\n ans+=s1[i];\n i++;j++;\n }\n if(j<s2.size())\n ans+=s2[j];\n \n }\n return ans;\n | 1 | 0 | ['C', 'C++'] | 0 |
reformat-the-string | Easy Python Solution | easy-python-solution-by-lizz04-s8zb | ``` \n\tdef reformat(self, s: str) -> str:\n digit=[]\n char=[]\n for i in s:\n if i>=\'0\' and i<=\'9\':\n di | Lizz04 | NORMAL | 2021-12-26T09:15:23.161671+00:00 | 2021-12-26T09:15:23.161713+00:00 | 137 | false | ``` \n\tdef reformat(self, s: str) -> str:\n digit=[]\n char=[]\n for i in s:\n if i>=\'0\' and i<=\'9\':\n digit.append(i)\n else:\n char.append(i)\n n1=len(digit)\n n2=len(char)\n if abs(n1-n2)>1:\n return \'\'\n else:\n ans=""\n if n1>n2:\n for i in range(n2):\n ans+=digit[i]\n ans+=char[i]\n if n1!=n2:\n ans+=digit[-1]\n else:\n for i in range(n1):\n ans+=char[i]\n ans+=digit[i]\n if n1!=n2:\n ans+=char[-1]\n return ans | 1 | 0 | ['Python'] | 0 |
reformat-the-string | Rust | rust-by-mee_ci-2w00 | \n\nstruct Solution{}\nimpl Solution {\n pub fn reformat(s: String) -> String {\n let mut sr = String::from("");\n let mut vsr:Vec<char> = vec! | Mee_CI | NORMAL | 2021-12-07T04:51:29.826846+00:00 | 2021-12-07T04:51:29.826881+00:00 | 37 | false | ```\n\nstruct Solution{}\nimpl Solution {\n pub fn reformat(s: String) -> String {\n let mut sr = String::from("");\n let mut vsr:Vec<char> = vec![];\n let mut vnum : Vec<char> = vec![];\n for i in s.chars(){\n if i.is_digit(10){\n vnum.push(i);\n }else{\n vsr.push(i);\n }\n }\n if vsr.len() > 0 && vnum.len() > 0{\n if vnum.len() >= vsr.len(){\n if vnum.len() - vsr.len() <= 1{\n for (i,vi) in vnum.iter().enumerate(){\n sr += &(*vi.to_string());\n for (_,vj) in vsr.iter().enumerate().skip(i){\n sr += &(*vj.to_string());\n break;\n }\n }\n }\n }else if vsr.len() >= vnum.len(){\n if vsr.len() - vnum.len() <= 1 {\n for (i,vi) in vsr.iter().enumerate(){\n sr += &(*vi.to_string());\n for (_,vj) in vnum.iter().enumerate().skip(i){\n sr += &(*vj.to_string());\n break;\n }\n }\n }\n }\n sr\n }else if vsr.len() == 1 && vnum.len() == 0{\n sr = vsr[0].to_string();\n return sr;\n }else if vsr.len() == 0 && vnum.len() ==1 {\n sr = vnum[0].to_string();\n return sr;\n }else{\n return String::from("");\n } \n }\n}\n\nfn main(){\n println!("{:?}",Solution::reformat("covid2019".to_string()));\n \n}\n#[cfg(test)]\nmod test{\n use crate::*;\n\n #[test]\n fn main_test(){\n assert_eq!(Solution::reformat("a0b1c2".to_string()),"0a1b2c");\n assert_eq!(Solution::reformat("leetcode".to_string()),"");\n assert_eq!(Solution::reformat("1229857369".to_string()),"");\n assert_eq!(Solution::reformat("covid2019".to_string()),"c2o0v1i9d");\n assert_eq!(Solution::reformat("ab123".to_string()),"1a2b3");\n assert_eq!(Solution::reformat("j".to_string()),"j");\n assert_eq!(Solution::reformat("a12bcd".to_string()),"");\n } \n}\n\n``` | 1 | 0 | ['Rust'] | 0 |
reformat-the-string | C++ | Faster than 100% || well commented | c-faster-than-100-well-commented-by-real-epxw | To start I read the problem and wrote down some thoughts on how i would solve and what i needed to look for. the order of the alg was a little different than th | realphilycheese | NORMAL | 2021-11-29T06:01:22.233093+00:00 | 2021-11-29T06:05:08.076871+00:00 | 82 | false | To start I read the problem and wrote down some thoughts on how i would solve and what i needed to look for. the order of the alg was a little different than the notes because they were just notes:\n\nCheck number of chars\nCheck number of digits\n\tpush chars to a vector and digits to a vector\n\nIf chars > digits ? Start with chars then digits\nIf chars<digits ? Start with digits then chars\nIf chars==digits then start with chars then digits\n\nMake sure difference between them isn\u2019t greater than 1\n\nWhen one is larger than the other then for loop up until smallest number and push last value at end outside of loop\n\n\t\n\nIf either chars or digits ==0 ? Return an empty sttring\n\n```\nclass Solution {\npublic:\n string reformat(string s) {\n int letters = 0;\n int digits = 0;\n vector<char> dig;\n vector<char>lettr;\n \n for (int i =0; i<s.length(); i++) // iterate through the string and just check if the value is a letter or digit. increment the corresponding counter and push the value to the corresponding vector that i created.\n {\n if(isdigit(s[i])) \n {\n digits++;\n dig.push_back(s[i]);\n }\n if (isalpha(s[i])){\n letters++;\n lettr.push_back(s[i]);\n }\n } \n \n if(letters ==0 && digits ==0)return ""; // as in my notes once you have the number of digits and letters, if both values are =0 then return a blank string\n\t\t\telse if ((letters==1 && digits ==0)|| (letters ==0 && digits ==1)) // following the given example, check if the string is simply one digit or one letter and if so return the string\n {\n return s;\n }\n\t\t\n s=""; // now set the original string to empty so i can start pushing the values to it again\n\t\t \n if(letters > digits) // if i have more letters than digits\n {\n if(letters-digits > 1) return ""; // if i have more letters than digits but the differnce is greater than 1 it means i will have letters next to eachother at the end which we dont want so return an empty string\n else{\n for (int i=0; i<dig.size();i++) //as in my notes, if i determine there are more letters than digits, then create a loop that runs per the size of the DIGITS vector\n {\n s+=lettr[i];\n s+=dig[i];\n }\n s+=lettr[lettr.size()-1]; //then i can add the remaining LETTER value from the letter vector \n }\n }\n else if(digits > letters)//// if i have more digits than letters\n {\n if(digits-letters > 1) return "";\n else{\n for (int i=0; i<lettr.size();i++) //because we have more digits than letters, run the loop per the size of the LETTERS vector\n {\n s+=dig[i];\n s+=lettr[i];\n }\n s+=dig[dig.size()-1]; //at the end add the remaining DIGIT from the digits vector\n }\n }\n else{ // if i have the same number of digits and letters then re add them in letter, digit order (you can do digit, letter order if you wish just change the order of adding the values within the loop)\n for (int i=0; i<lettr.size();i++) \n {\n s+=lettr[i];\n s+=dig[i];\n }\n \n }\n \n \n return s;\n }\n};\n\n``` | 1 | 0 | [] | 1 |
reformat-the-string | python if else tree | python-if-else-tree-by-vigneswar_a-cd0o | \nclass Solution:\n def reformat(self, s: str) -> str:\n \n nums=[]\n chars=[]\n \n for c in s:\n if c.isdigit( | Vigneswar_A | NORMAL | 2021-11-28T17:03:03.809378+00:00 | 2021-11-28T17:03:03.809422+00:00 | 42 | false | ```\nclass Solution:\n def reformat(self, s: str) -> str:\n \n nums=[]\n chars=[]\n \n for c in s:\n if c.isdigit():\n nums.append(c)\n else:\n chars.append(c)\n \n if len(nums)==len(chars):\n string=""\n for i in range(len(nums)):\n string+=nums[i]+chars[i]\n return string\n \n elif len(nums)==len(chars)-1:\n string=chars[0]\n for i in range(1,len(chars)):\n string+=nums[i-1]+chars[i]\n return string\n \n elif len(nums)==len(chars)+1:\n string=nums[0]\n for i in range(1,len(nums)):\n string+=chars[i-1]+nums[i]\n return string\n \n else:\n return \'\'\n\t\t\t``` | 1 | 0 | [] | 0 |
reformat-the-string | C++ || 90 % || COUNTING LETTER AND DIGITS | c-90-counting-letter-and-digits-by-anas_-wpa9 | \n// Algorithm:\n// 1.In this we first count the number of letter and digits in the string .\n// 2.After counting if the difference is >1 return false \n// 3.if | anas_parvez | NORMAL | 2021-11-16T15:46:44.544063+00:00 | 2021-11-16T15:46:44.544090+00:00 | 52 | false | ```\n// Algorithm:\n// 1.In this we first count the number of letter and digits in the string .\n// 2.After counting if the difference is >1 return false \n// 3.if letters are more then the word must start with a letter and vice versa \n// 4.Return the String \n\nclass Solution {\npublic:\n string reformat(string s) {\n string str="";\n int digit=0,letter=0;\n vector<char>d;\n vector<char>l;\n for(int i=0;i<s.size();i++){\n if(isdigit(s[i])){\n digit++;\n d.push_back(s[i]);\n }\n else{\n letter++;\n l.push_back(s[i]);\n }\n }\n if(abs(digit-letter)>1)\n return "";\n if(digit>=letter){\n int i=0,j=0;\n while(i<d.size()&&i<l.size()){\n str+=d[i];\n str+=l[i];\n i++;\n }\n if(i!=d.size())\n str+=d[i];\n }\n else{\n int i=0,j=0;\n while(i<d.size()&&i<l.size()){\n str+=l[i];\n str+=d[i];\n i++;\n }\n str+=l[i];\n }\n return str;\n }\n};\n``` | 1 | 0 | [] | 0 |
reformat-the-string | [Python3] zip() | python3-zip-by-nuno-dev1-t4ez | \nclass Solution:\n def reformat(self, s: str) -> str:\n s1=\'\'.join([x for x in s if x.isalpha()])\n s2=\'\'.join([x for x in s if x.isnumeri | nuno-dev1 | NORMAL | 2021-10-28T19:54:04.595649+00:00 | 2021-10-29T20:44:52.555909+00:00 | 81 | false | ```\nclass Solution:\n def reformat(self, s: str) -> str:\n s1=\'\'.join([x for x in s if x.isalpha()])\n s2=\'\'.join([x for x in s if x.isnumeric()])\n if abs(len(s1)-len(s2))>1: \n return \'\'\n if len(s1)<len(s2):\n s1,s2=s2,s1\n return \'\'.join([x+y for x,y in zip(s1,s2)]) + (s1[-1] if len(s1)>len(s2) else \'\')\n``` | 1 | 0 | [] | 0 |
reformat-the-string | JAVA EASY SOLUTION | java-easy-solution-by-aniket7419-n4m0 | \nclass Solution {\n public String reformat(String s) {\n ArrayList<Character> cha=new ArrayList<Character>();\n ArrayList<Character> in=new Ar | aniket7419 | NORMAL | 2021-10-24T07:36:23.532571+00:00 | 2021-10-24T07:36:23.532616+00:00 | 67 | false | ```\nclass Solution {\n public String reformat(String s) {\n ArrayList<Character> cha=new ArrayList<Character>();\n ArrayList<Character> in=new ArrayList<Character>();\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)>=97)\n cha.add(s.charAt(i));\n else\n in.add(s.charAt(i));\n }\n String result="";\n if(Math.abs(cha.size()-in.size())>1)\n return result;\n else{\n \n \n if(cha.size()>in.size()){\n for(int i=0;i<in.size();i++)\n result+=cha.get(i)+""+in.get(i);\n result+=cha.get(cha.size()-1);\n }\n else{\n for(int i=0;i<cha.size();i++)\n result+=in.get(i)+""+cha.get(i);\n if(in.size()>cha.size())\n result+=in.get(in.size()-1);\n }\n \n \n }\n\n \n \n return result;\n \n }\n}\n``` | 1 | 0 | [] | 0 |
reformat-the-string | Very Easy approach in C++ | very-easy-approach-in-c-by-msy15-s0g3 | \nclass Solution {\npublic:\n string reformat(string s) {\n int n=s.size();\n vector<char>a;\n vector<char>b;\n \n for(int | MSY15 | NORMAL | 2021-10-07T14:41:35.768368+00:00 | 2021-10-07T14:41:35.768417+00:00 | 70 | false | ```\nclass Solution {\npublic:\n string reformat(string s) {\n int n=s.size();\n vector<char>a;\n vector<char>b;\n \n for(int i=0;i<n;i++)\n {\n if(isalpha(s[i]))\n {\n a.push_back(s[i]);\n }\n else\n {\n b.push_back(s[i]);\n }\n }\n int n1=a.size();\n int n2=b.size();\n string ans="";\n if(abs(n1-n2)>1)\n return ans; \n else\n {\n if(n1==n2)\n {\n for(int i=0;i<n1;i++)\n {\n ans+=a[i];\n ans+=b[i];\n }\n }\n else if(n1>n2)\n {\n int i=0;\n for(;i<n2;i++)\n {\n ans+=a[i];\n ans+=b[i];\n }\n ans+=a[i];\n }\n else if(n1<n2)\n {\n int i=0;\n for( ;i<n1;i++)\n {\n ans+=b[i];\n ans+=a[i];\n \n }\n ans+=b[i];\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
reformat-the-string | Reformat the String | Java | reformat-the-string-java-by-deleted_user-rded | \nclass Solution {\n public String reformat(String s) {\n \n //Edge Case 1: Null string / Length of the string is 0\n if (s.length() == | deleted_user | NORMAL | 2021-09-06T15:21:37.067237+00:00 | 2021-09-06T15:21:37.067292+00:00 | 210 | false | ```\nclass Solution {\n public String reformat(String s) {\n \n //Edge Case 1: Null string / Length of the string is 0\n if (s.length() == 0 || s.length() == 1) {\n return s;\n }\n \n StringBuilder digits = new StringBuilder();\n StringBuilder alphabets = new StringBuilder();\n \n // Separate Digits and Letters from the string\n for (char token : s.toCharArray()) {\n if (Character.isLetter (token)) {\n alphabets.append (token);\n }\n \n if (Character.isDigit (token)) {\n digits.append (token);\n }\n }\n \n // Edge Case 2: No digits or no Letters present in anyone / both of the strings\n if (digits.length() == 0 || alphabets.length() == 0) {\n return "";\n }\n \n // Edge Case 3: The different between the frequency of letters and digits is more than 1\n if (Math.abs (digits.length() - alphabets.length()) > 1) {\n return "";\n }\n \n StringBuilder result = new StringBuilder();\n int aIndex = 0;\n int dIndex = 0;\n boolean digitStart = false;\n \n // If the frequency of digits is more than that of letters, start the result string with a digit\n if (digits.length() > alphabets.length()) {\n result.append (digits.charAt (dIndex));\n digitStart = true;\n dIndex++;\n }\n \n // If the frequency of alphabets is more than that of digits, start the result string with a alphabet\n if (digits.length() < alphabets.length()) {\n System.out.println ("Hello");\n result.append (alphabets.charAt (aIndex));\n aIndex++;\n }\n\n while (dIndex < digits.length() && aIndex < alphabets.length()) {\n \n // Depending on the start character, append the digit first or the alphabet first\n if (digitStart) {\n result.append (alphabets.charAt (aIndex));\n result.append (digits.charAt (dIndex));\n }\n else {\n result.append (digits.charAt (dIndex));\n result.append (alphabets.charAt (aIndex));\n }\n aIndex++;\n dIndex++;\n }\n return result.toString();\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
reformat-the-string | Java O(N) time, O(1) space, two pointers | java-on-time-o1-space-two-pointers-by-mi-dykb | Instead of copying digits and letters to separate lists, maintain a pointer per type. Final result shouldn\'t count as O(N) space as it\'s not used apart return | migfulcrum | NORMAL | 2021-07-26T07:37:44.346651+00:00 | 2021-07-26T07:38:00.747966+00:00 | 89 | false | Instead of copying digits and letters to separate lists, maintain a pointer per type. Final result shouldn\'t count as O(N) space as it\'s not used apart returning the result.\n\n```\n public String reformat(String s) {\n int n = s.length();\n int digits = 0;\n for(int i = 0; i < n; i++) {\n if(Character.isDigit(s.charAt(i))) {\n digits++;\n }\n }\n int letters = n - digits;\n if(Math.abs(letters - digits) > 1) return "";\n \n int dIdx = 0;\n int lIdx = 0;\n\n StringBuilder res = new StringBuilder();\n \n while(res.length() < n) {\n while(lIdx < n && Character.isDigit(s.charAt(lIdx))) {\n lIdx++;\n }\n while(dIdx < n && !Character.isDigit(s.charAt(dIdx))) {\n dIdx++;\n }\n if(digits > letters) {\n res.append(s.charAt(dIdx++));\n if(res.length() < n) res.append(s.charAt(lIdx++));\n } else {\n res.append(s.charAt(lIdx++));\n if(res.length() < n) res.append(s.charAt(dIdx++));\n }\n \n }\n return res.toString();\n }\n``` | 1 | 0 | [] | 0 |
reformat-the-string | Java Solution Faster than 87% O(n) | java-solution-faster-than-87-on-by-rar34-i0lu | In this solution I use two Queues here to group both digits and non digits together. You can then loop until both Queues are empty and append the oposite of the | rar349 | NORMAL | 2021-07-16T01:05:16.494088+00:00 | 2021-07-16T01:05:16.494125+00:00 | 78 | false | In this solution I use two Queues here to group both digits and non digits together. You can then loop until both Queues are empty and append the oposite of the last character type onto your result starting with the character type that we have the most of.\n\nThis solution is O(n). It is also important to realize that my use of a Queue is completely arbitrary for this problem and the data structure used doesn\'t make any difference. I could have used a Stack or even a simple ArrayList.\n\n```\nclass Solution {\n \n public String reformat(String s) {\n LinkedList<Character> nums = new LinkedList<>();\n LinkedList<Character> chars = new LinkedList<>();\n \n char[] charArr = s.toCharArray();\n \n for(char c : charArr) {\n if(Character.isDigit(c)) nums.offer(c);\n else chars.offer(c);\n }\n \n if(Math.abs(nums.size() - chars.size()) > 1) return "";\n \n StringBuilder toReturn = new StringBuilder();\n boolean lastWasDigit = chars.size() > nums.size();\n while(!nums.isEmpty() || !chars.isEmpty()) {\n char c = !lastWasDigit ? nums.poll() : chars.poll();\n \n lastWasDigit = !lastWasDigit;\n toReturn.append(c);\n }\n \n return toReturn.toString();\n }\n \n}\n``` | 1 | 0 | [] | 0 |
reformat-the-string | Java Solution Using StringBuilders and Helper Method to Force Start Larger String | java-solution-using-stringbuilders-and-h-svc9 | ```\npublic String reformat(String s) {\n\tStringBuilder alpha = new StringBuilder();\n\tStringBuilder digit = new StringBuilder();\n\tfor (char c : s.toCharArr | chino8 | NORMAL | 2021-07-09T01:31:09.506468+00:00 | 2021-07-09T01:31:09.506531+00:00 | 61 | false | ```\npublic String reformat(String s) {\n\tStringBuilder alpha = new StringBuilder();\n\tStringBuilder digit = new StringBuilder();\n\tfor (char c : s.toCharArray()) {\n\t\tif (Character.isDigit(c)) {\n\t\t\tdigit.append(c);\n\t\t} else if (Character.isLetter(c)) {\n\t\t\talpha.append(c);\n\t\t}\n\t}\n\n\tif (Math.abs(alpha.length() - digit.length()) > 1) {\n\t\treturn "";\n\t}\n\n\treturn mergeStrings(alpha, digit);\n}\n\nprivate String mergeStrings(StringBuilder sb1, StringBuilder sb2) {\n\t// Make sure sb1.length is always smaller\n\tif (sb1.length() > sb2.length()) {\n\t\treturn mergeStrings(sb2, sb1);\n\t}\n\n\tint sb2Index = 0;\n\tint sb1Index = 0;\n\tStringBuilder answer = new StringBuilder();\n\twhile (sb2Index < sb2.length() || sb1Index < sb1.length()) {\n\t\tif (sb2Index < sb2.length()) {\n\t\t\tanswer.append(sb2.charAt(sb2Index));\n\t\t\tsb2Index++;\n\t\t}\n\n\t\tif (sb1Index < sb1.length()) {\n\t\t\tanswer.append(sb1.charAt(sb1Index));\n\t\t\tsb1Index++;\n\t\t}\n\t}\n\n\treturn answer.toString();\n} | 1 | 0 | [] | 1 |
reformat-the-string | Python 3 : SIMPLE EASY + 36 ms, 97.74% faster | python-3-simple-easy-36-ms-9774-faster-b-qgjz | \nclass Solution:\n def reformat(self, s: str) -> str:\n \n if len(s) > 1 and (s.isalpha() or s.isdigit()) :\n return \'\'\n\n | rohitkhairnar | NORMAL | 2021-07-06T13:48:41.644004+00:00 | 2021-07-06T14:00:16.830502+00:00 | 281 | false | ```\nclass Solution:\n def reformat(self, s: str) -> str:\n \n if len(s) > 1 and (s.isalpha() or s.isdigit()) :\n return \'\'\n\n ints = \'\'\n alpha = \'\'\n for i in s :\n if i.isalpha() :\n alpha += i\n else:\n ints += i\n \n res = \'\'\n n = min(len(ints),len(alpha))\n for j in range(n) :\n if len(ints) < len(alpha) :\n res += alpha[j] + ints[j]\n else :\n res += ints[j] + alpha[j]\n\n return res + alpha[n:] + ints[n:] \n\n```\nAfter creating 2 strings with digits and aplhabets , we will merge them alternately\n* if len(ints) > len(alpha) -> eg : ***\'ab123\'***\n we need output ***\'1a2b3\'*** , therefore we do ( res += ints[j] + alpha[j] )\n* similarly if len(ints) < len(alpha) -> eg : ***\'abc12\'***\n we need output ***\'a1b2c\'*** , therefore we do ( res += alpha[j] + ints[j] )\n \n* *( res + alpha[n:] + ints[n:] )* --> for concatanation of remaining elements of string with greater length to res . \n\n**please upvote if u like : )** | 1 | 0 | ['Python', 'Python3'] | 0 |
reformat-the-string | [Java] Clean Code | java-clean-code-by-algorithmimplementer-998i | ```java\npublic String reformat(String s) {\n\tif (s == null || s.isEmpty()) return s;\n\n\tLinkedList letters = new LinkedList<>();\n\tLinkedList digits = new | algorithmimplementer | NORMAL | 2021-07-01T04:51:10.450685+00:00 | 2021-07-01T04:51:10.450730+00:00 | 67 | false | ```java\npublic String reformat(String s) {\n\tif (s == null || s.isEmpty()) return s;\n\n\tLinkedList<Character> letters = new LinkedList<>();\n\tLinkedList<Character> digits = new LinkedList<>();\n\n\tfor (char ch : s.toCharArray()) {\n\t\tif (Character.isLetter(ch)) letters.add(ch);\n\t\tif (Character.isDigit(ch)) digits.add(ch);\n\t}\n\t\n\tint diff = letters.size() - digits.size();\n\t\n\tif (Math.abs(diff) >= 2) return "";\n\t\n\tLinkedList<Character> bigger = diff >= 0 ? letters : digits;\n\tLinkedList<Character> smaller = diff >= 0 ? digits : letters;\n\t\n\tStringBuilder sb = new StringBuilder();\n\t\n\twhile (!bigger.isEmpty() || !smaller.isEmpty()) {\n\n\t\tif (!bigger.isEmpty())\n\t\t\tsb.append(bigger.removeFirst());\n\t\tif (!smaller.isEmpty())\n\t\t\tsb.append(smaller.removeFirst());\n\t}\n\treturn sb.toString();\n} | 1 | 0 | [] | 0 |
reformat-the-string | C++ || 0ms runtime || 100% faster 0(N) sol | c-0ms-runtime-100-faster-0n-sol-by-saite-jh1u | \nclass Solution {\npublic:\n string reformat(string s) {\n vector<char> v1;\n vector<char> v2;\n //v1 contains the digits and v2 contai | saiteja_balla0413 | NORMAL | 2021-05-20T13:53:34.968203+00:00 | 2021-05-20T13:53:34.968246+00:00 | 69 | false | ```\nclass Solution {\npublic:\n string reformat(string s) {\n vector<char> v1;\n vector<char> v2;\n //v1 contains the digits and v2 contains the alphabets\n for(auto c:s)\n {\n if(isdigit(c))\n {\n v1.push_back(c);\n }\n else{\n v2.push_back(c);\n }\n }\n string res="";\n int len1=v1.size();\n int len2=v2.size();\n if(len1==len2 || len1==len2+1 || len2==len1+1)\n {\n //we can able to form a string\n char num=\' \';\n if(len1>len2){\n num=v1.back();\n v1.pop_back();\n }\n else if(len2>len1){ \n res.push_back(v2.back());\n v2.pop_back();\n }\n //now both v1 and v2 contains same length\n len1=v1.size();\n for(int i=0;i<len1;i++)\n {\n res.push_back(v1.back());\n res.push_back(v2.back());\n v1.pop_back();\n v2.pop_back();\n }\n if(num!=\' \')\n {\n res.push_back(num);\n }\n }\n return res;\n }\n};\n``` | 1 | 0 | [] | 0 |
reformat-the-string | easy c++ solution(with comments) faster than 95% | easy-c-solutionwith-comments-faster-than-jikr | \tclass Solution {\n\tpublic:\n\t\tstring reformat(string s) {\n\t\t\tint n=s.size();\n\t\t\tstring num="";// one for storing digits\n\t\t\tstring alpha="";// o | shubhamsinhanitt | NORMAL | 2021-04-08T17:03:25.571117+00:00 | 2021-04-08T17:03:25.571160+00:00 | 40 | false | \tclass Solution {\n\tpublic:\n\t\tstring reformat(string s) {\n\t\t\tint n=s.size();\n\t\t\tstring num="";// one for storing digits\n\t\t\tstring alpha="";// one for storing characters\n\t\t\tfor(int i=0;i<n;i++)\n\t\t\t{\n\t\t\t\tif(isalpha(s[i]))\n\t\t\t\t{\n\t\t\t\t\talpha+=s[i];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tnum+=s[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\tstring ans="";\n\t\t\tint first=num.size();\n\t\t\tint second=alpha.size();\n\t\t\tif(abs(first-second)>1)// this is the case where its impossible to create a alternate string so return empty string\n\t\t\t{\n\t\t\t\treturn ans;\n\t\t\t}\n\t\t\tint i;\n\t\t\tint j;\n\t\t\tif(first==second)// if both strings are equal then just start with any we will get alternate pattern\n\t\t\t{\n\t\t\t\tfor(i=0,j=0;i<first,j<second;i++,j++)\n\t\t\t\t{\n\t\t\t\t\tans+=num[i];\n\t\t\t\t\tans+=alpha[j];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(first>second)// if first is greater so start with first one and now put characters alternately\n\t\t\t{\n\t\t\t\tans+=num[0];\n\t\t\t\tfor(i=1,j=0;i<first,j<second;i++,j++)\n\t\t\t\t{\n\t\t\t\t\tans+=alpha[j];\n\t\t\t\t\tans+=num[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(first<second)// if second is greater so start with second one and now put characters alternately\n\t\t\t{\n\t\t\t\tans+=alpha[0];\n\t\t\t\tfor(i=0,j=1;i<first,j<second;i++,j++)\n\t\t\t\t{\n\t\t\t\t\tans+=num[i];\n\t\t\t\t\tans+=alpha[j];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ans;\n\n\t\t}\n\t}; | 1 | 0 | [] | 0 |
reformat-the-string | Python 3 , Runtime faster than 97.30% and Memory usage less than 89.38% | python-3-runtime-faster-than-9730-and-me-cefq | \nclass Solution:\n def reformat(self, s: str) -> str:\n strs = ""\n nums = ""\n out = ""\n if len(s) == 1 :\n return | sbcyu0421 | NORMAL | 2021-03-02T16:46:35.038431+00:00 | 2021-03-02T16:46:35.038466+00:00 | 170 | false | ```\nclass Solution:\n def reformat(self, s: str) -> str:\n strs = ""\n nums = ""\n out = ""\n if len(s) == 1 :\n return s\n for i in s :\n if ord(i) < 97 :\n nums += i\n else :\n strs += i\n if strs == "" or nums == "":\n return ""\n elif len(strs) > len(nums):\n for j in range(len(nums)) :\n out += strs[j]+nums[j]\n out += strs[len(nums):]\n else :\n for k in range(len(strs)) :\n out += nums[k]+strs[k]\n out += nums[len(strs):]\n return out\n``` | 1 | 0 | [] | 0 |
reformat-the-string | [Java] Very easy to understand | java-very-easy-to-understand-by-ra1n-4j1j | \nclass Solution {\n public String reformat(String s) {\n if (s == null || s.length() == 0 || s.length() == 1) {\n return s;\n }\n | ra1n | NORMAL | 2021-02-22T00:52:00.066956+00:00 | 2021-02-22T00:52:00.066985+00:00 | 284 | false | ```\nclass Solution {\n public String reformat(String s) {\n if (s == null || s.length() == 0 || s.length() == 1) {\n return s;\n }\n StringBuilder num = new StringBuilder();\n StringBuilder alpha = new StringBuilder();\n \n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (Character.isDigit(c)) {\n num.append(c);\n } else if (Character.isLetter(c)) {\n alpha.append(c);\n }\n }\n if (num.length() == 0 || alpha.length() == 0 || num == null || alpha == null) {\n return "";\n }\n int i = 0, j = 0;\n int nlen = num.length();\n int alen = alpha.length();\n StringBuilder result = new StringBuilder();\n while (i < num.length() && j < alpha.length()) {\n char c1 = num.charAt(i++);\n char c2 = alpha.charAt(j++);\n if (nlen > alen) {\n result.append(c1).append(c2);\n } else {\n result.append(c2).append(c1);\n }\n }\n if (i < num.length()) {\n result.append(num.charAt(i));\n }\n if (j < alpha.length()) {\n result.append(alpha.charAt(j));\n }\n return result.toString();\n }\n}\n``` | 1 | 1 | [] | 0 |
reformat-the-string | C++ Wiggle sort II same logic. | c-wiggle-sort-ii-same-logic-by-codebush-4shd | \n\nclass Solution {\npublic:\n string reformat(string s) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n int | codebush | NORMAL | 2021-01-23T06:52:47.996486+00:00 | 2021-01-23T06:52:47.996516+00:00 | 74 | false | ```\n\n```class Solution {\npublic:\n string reformat(string s) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n int n = s.size(),a=0,b=0;\n string s2(s);\n for(int i=0;i<n;i++){\n if(s[i]>=\'0\' and s[i]<=\'9\')a++;\n else b++;\n }\n if(abs(a-b)>1)return "";\n else if(a>=b) sort(s2.begin(), s2.end());\n else if(b>a) sort(s2.rbegin(), s2.rend());\n int j = (n - 1) / 2, k = n - 1;\n for (int i = 0; i < n; ++i)\n s[i] = i & 1 ? s2[k--]: s2[j--];\n return s;\n }\n}; | 1 | 0 | [] | 1 |
reformat-the-string | Python solution | python-solution-by-gabichoi-i2w6 | \tdef reformat(self, s):\n\t\tnumbers = [c for c in s if c.isdigit()]\n letters = [c for c in s if c.isalpha()]\n diff = abs(len(numbers) - len(le | gabichoi | NORMAL | 2021-01-21T08:29:14.499657+00:00 | 2021-01-21T08:29:14.499696+00:00 | 149 | false | \tdef reformat(self, s):\n\t\tnumbers = [c for c in s if c.isdigit()]\n letters = [c for c in s if c.isalpha()]\n diff = abs(len(numbers) - len(letters))\n if len(numbers) > len(letters):\n return self.helper(numbers, letters, diff)\n else:\n return self.helper(letters, numbers, diff)\n \n def helper(self, longer, shorter, diff):\n ans = \'\'\n if diff > 1:\n return ans\n elif diff == 1:\n ans += longer.pop()\n while shorter or longer:\n ans += shorter.pop() + longer.pop()\n return ans | 1 | 0 | ['Stack', 'Python'] | 0 |
reformat-the-string | Python 3, Zip, Join, Explained | python-3-zip-join-explained-by-lucliu-vekh | Explaination:\nAll letters are in a list, and all digits are in another list.\nUse zip() fucntion to iterate both lists, add the last remaining letter or digit | lucliu | NORMAL | 2020-12-31T02:32:36.763853+00:00 | 2020-12-31T02:32:36.763897+00:00 | 257 | false | Explaination:\nAll letters are in a list, and all digits are in another list.\nUse zip() fucntion to iterate both lists, add the last remaining letter or digit accordingly.\n~~~\nclass Solution:\n def reformat(self, s: str) -> str:\n al, dig, res = "", "", ""\n for c in s:\n if c.isalpha(): al += c\n else: dig += c\n if abs(len(al)-len(dig)) > 1: return ""\n if len(al) > len(dig):\n res = "".join([(l+n) for l, n in zip(al, dig)])\n res += al[-1]\n elif len(al) < len(dig):\n res = "".join([(n+l) for n, l in zip(dig, al)])\n res += dig[-1]\n else:\n res = "".join([(n+l) for n, l in zip(dig, al)])\n return res\n~~~\n\n#Runtime: 36 ms, faster than 96.03% of Python3 online submissions for Reformat The String.\n#Memory Usage: 14 MB, less than 99.24% of Python3 online submissions for Reformat The String. | 1 | 0 | ['Python3'] | 0 |
reformat-the-string | 4ms easy to understand C++ | 4ms-easy-to-understand-c-by-xzci-cw93 | \nclass Solution {\npublic:\n string reformat(string s) {\n\tstring ans(s.size(), \' \');\n int charnum = 0;\n int num = 0;\n \n bool flag = fal | xzci | NORMAL | 2020-12-25T13:28:22.794846+00:00 | 2020-12-25T13:28:22.794875+00:00 | 81 | false | ```\nclass Solution {\npublic:\n string reformat(string s) {\n\tstring ans(s.size(), \' \');\n int charnum = 0;\n int num = 0;\n \n bool flag = false;\n for (auto i : s) {\n if(isalpha(i)) \n charnum++; \n else \n num++;\n }\n \n\tif (abs(num - charnum) > 1) \n return "";\n int index_num;\n int index_char;\n if(num > charnum) {\n index_num = 0;\n index_char = 1;\n }\n else {\n index_num = 1;\n index_char = 0;\n }\n\n\tfor (auto i : s) {\n if(isalpha(i)) {\n ans[index_char] = i;\n index_char += 2; \n } else { \n ans[index_num] = i;\n index_num += 2; \n }\n }\n\treturn ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
reformat-the-string | My Java Solution with the steps | my-java-solution-with-the-steps-by-vrohi-792k | \n// 1. Create two list for numbers and characters each.\n// 2. If the diff between these two list is >= 2, return "" as we cant get any answer.\n// 3. Use a bo | vrohith | NORMAL | 2020-10-02T14:27:35.331677+00:00 | 2020-10-02T14:27:35.331722+00:00 | 332 | false | ```\n// 1. Create two list for numbers and characters each.\n// 2. If the diff between these two list is >= 2, return "" as we cant get any answer.\n// 3. Use a boolean variable to switch between digit and characters.\n// 4. Always start the first letter with the max count one, ie max(digit, letter) count\n\nclass Solution {\n public String reformat(String s) {\n List<Character> digit = new ArrayList<>();\n List<Character> letter = new ArrayList<>();\n for (char ch: s.toCharArray()) {\n if (Character.isDigit(ch))\n digit.add(ch);\n else\n letter.add(ch);\n }\n if (Math.abs(digit.size() - letter.size()) >= 2)\n return "";\n StringBuilder sb = new StringBuilder();\n boolean isNumber = (digit.size() - letter.size() < 0) ? false : true; // here i actuallu checks for the maximum size from the two.\n for (int i=0; i<s.length(); i++) {\n if (isNumber) {\n if (digit.size() > 0) {\n sb.append(digit.remove(0));\n \n }\n }\n else {\n if (letter.size() > 0)\n sb.append(letter.remove(0));\n }\n isNumber = !isNumber;\n }\n return sb.toString();\n }\n}\n``` | 1 | 0 | ['String', 'Java'] | 0 |
reformat-the-string | c++ using template or func_ptr approaches (8ms , 98.91%) | c-using-template-or-func_ptr-approaches-qpcdd | first determine order (digit or alpha first)\n then take care of no-solution cases\n then use the two iterators to alternate in the found order digits and alpha | michelusa | NORMAL | 2020-09-28T12:12:45.598869+00:00 | 2020-09-29T01:21:43.304634+00:00 | 53 | false | * first determine order (digit or alpha first)\n* then take care of no-solution cases\n* then use the two iterators to alternate in the found order digits and alphas.\nThe add_alphanum takes a function parameter depending if asked to add either digit or alpha\ntemplate approach followed by func_ptr old school approach\n```\nclass Solution {\n private:\n template<typename F> \n auto add_alphanum( string::const_iterator scan, const string&s, F am_i, string& result) const {\n while (scan != cend(s) && !am_i(*scan) )\n ++scan;\n if (scan != cend(s)) {\n result.push_back(*scan);\n ++scan;\n }\n return scan;\n }\npublic:\n string reformat(const string& s) const {\n \n const size_t digits = count_if(cbegin(s), cend(s), [](const auto& x) {return isdigit(x);});\n\n if ( ((s.size() & 1) == 0) && (digits != s.size()/2 ))\n return "";\n if ( ((s.size() & 1) == 1) && (digits != s.size()/2) && (digits != s.size()/2 +1 ))\n return "";\n \n string result {""};\n\n auto scan = cbegin(s);\n auto it = cbegin(s);\n\n const auto lambda_is_digit = [] (const auto&x) { return isdigit(x); };\n const auto lambda_is_alpha = [] (const auto&x) { return isalpha(x); };\n\n if (digits == s.size()/2 + 1) {\n while ( scan != cend(s) || it != cend(s)) {\n scan = add_alphanum(scan, s, lambda_is_digit, result);\n it = add_alphanum(it, s, lambda_is_alpha, result);\n }\n } else {\n while (scan != cend(s) || it != cend(s)) {\n it = add_alphanum(it, s, lambda_is_alpha, result);\n scan = add_alphanum(scan, s, lambda_is_digit, result);\n }\n }\n\n return result;\n \n }\n};\n```\nusing func ptr:\n\n\n\n```\n private:\n auto add_alphanum( string::const_iterator scan, const string&s, int (*func_pointer) (int), string& result) const{\n while (scan != cend(s) && !func_pointer(*scan) )\n ++scan;\n if (scan != cend(s)) {\n result.push_back(*scan); \n ++scan;\n }\n return scan;\n }\n \npublic:\n string reformat(const string& s) const {\n \n const size_t digits = count_if(cbegin(s), cend(s), [](const auto& x) {return isdigit(x);});\n \n if ( ((s.size() & 1) == 0) && (digits != s.size()/2 ))\n return "";\n if ( ((s.size() & 1) == 1) && (digits != s.size()/2) && (digits != s.size()/2 +1 )) \n return "";\n \n string result {""};\n \n auto scan = cbegin(s);\n auto it = cbegin(s);\n if (digits == s.size()/2 + 1) { \n while ( scan != cend(s) || it != cend(s)) {\n scan = add_alphanum(scan, s, isdigit, result);\n it = add_alphanum(it, s, isalpha, result);\n }\n } else {\n while (scan != cend(s) || it != cend(s)) {\n it = add_alphanum(it, s, isalpha, result);\n scan = add_alphanum(scan, s, isdigit, result);\n }\n }\n \n return result;\n \n } | 1 | 0 | ['C'] | 0 |
reformat-the-string | Rust, 0ms, 100% | rust-0ms-100-by-qiuzhanghua-8by0 | rust\nimpl Solution {\n pub fn reformat(s: String) -> String {\n let v = s.as_bytes();\n let mut v1 = vec![];\n let mut v2 = vec![];\n | qiuzhanghua | NORMAL | 2020-08-28T02:19:52.046086+00:00 | 2020-08-28T02:19:52.046131+00:00 | 71 | false | ```rust\nimpl Solution {\n pub fn reformat(s: String) -> String {\n let v = s.as_bytes();\n let mut v1 = vec![];\n let mut v2 = vec![];\n for ch in v {\n if ch.is_ascii_digit() {\n v1.push(ch)\n } else {\n v2.push(ch);\n }\n }\n let mut ans = String::new();\n if (v1.len() as i32 - v2.len() as i32).abs() > 1 {\n return ans;\n }\n let mut p1 = &mut v1;\n let mut p2 = &mut v2;\n let mut start = 0;\n if p2.len() > p1.len() {\n p1 = &mut v2;\n p2 = &mut v1;\n }\n if p1.len() > p2.len() {\n ans.push(*p1[0] as char);\n start += 1;\n }\n for i in 0..p2.len() {\n ans.push(*p2[i] as char);\n ans.push(*p1[i + start] as char);\n }\n ans\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_reformat() {\n assert_eq!(\n Solution::reformat("a0b1c2".to_string()),\n "0a1b2c".to_string()\n );\n }\n\n #[test]\n fn test_reformat_02() {\n assert_eq!(Solution::reformat("leetcode".to_string()), "".to_string());\n }\n\n #[test]\n fn test_reformat_03() {\n assert_eq!(Solution::reformat("1229857369".to_string()), "".to_string());\n }\n\n #[test]\n fn test_reformat_04() {\n assert_eq!(\n Solution::reformat("covid2019".to_string()),\n "c2o0v1i9d".to_string()\n );\n }\n\n #[test]\n fn test_reformat_05() {\n assert_eq!(Solution::reformat("ab123".to_string()), "1a2b3".to_string());\n }\n}\n``` | 1 | 0 | [] | 0 |
reformat-the-string | JavaScript - O (n) 2 loops | javascript-o-n-2-loops-by-bernardsean-xj9e | \nTime complexity: O (s.length) + O (alphabet array.length) = O (n)\nSpace Complexity: O(s.length) = O (n);\n/**\n * @param {string} s\n * @return {string}\n */ | bernardsean | NORMAL | 2020-08-26T03:15:32.455747+00:00 | 2020-08-27T15:53:49.090133+00:00 | 50 | false | ```\nTime complexity: O (s.length) + O (alphabet array.length) = O (n)\nSpace Complexity: O(s.length) = O (n);\n/**\n * @param {string} s\n * @return {string}\n */\nvar reformat = function(s) {\n const al = [], nums = [];\n for (let ss of s.split(\'\')) {\n if (ss % 1 === 0) {\n nums.push(ss);\n } else {\n al.push(ss);\n }\n }\n\n const nn = nums.length, an = al.length, ans = [];\n \n if (s.length === 1) {\n return s;\n }\n \n if (an === 0 && nn === 0 || an > 0 && nn === 0 || nn > 0 && an === 0) {\n return "";\n }\n\n // a1b2c a1b2c3 1a2b3c4 <= check this because it can be length +/- 1\n if(an <= nn + 1 || an <= nn - 1 || nn <= an + 1 || nn <= an - 1) {\n for (let i = 0; i <= al.length; i++) {\n if( nn > an) {\n ans.unshift(nums[i]);\n ans.unshift(al[i]);\n } else {\n ans.unshift(al[i]);\n ans.unshift(nums[i]);\n }\n }\n return ans.join(\'\');\n }\n \n return "";\n};\n\n``` | 1 | 1 | [] | 0 |
reformat-the-string | JavaScript O(N) solution | javascript-on-solution-by-illitirit-hk52 | \nvar reformat = function(s) {\n if (s.length <= 1) return s;\n \n const result = [];\n const letters = s.match(/[a-zA-Z]/g) || [];\n const nums = s.match( | illitirit | NORMAL | 2020-07-17T18:38:17.046733+00:00 | 2020-07-17T18:38:33.279473+00:00 | 172 | false | ```\nvar reformat = function(s) {\n if (s.length <= 1) return s;\n \n const result = [];\n const letters = s.match(/[a-zA-Z]/g) || [];\n const nums = s.match(/[0-9]/g) || [];\n \n if (!letters.length || !nums.length) return \'\'\n \n const larger = letters.length > nums.length ? \'letters\' : \'nums\';\n\n while (letters.length || nums.length) {\n let letter = letters.pop();\n let num = nums.pop();\n larger === \'letters\' ? result.push(letter, num) : result.push(num, letter);\n }\n\n return result.join(\'\');\n};\n ``` | 1 | 0 | ['JavaScript'] | 0 |
reformat-the-string | Simple basic flow seperate lists | simple-basic-flow-seperate-lists-by-soha-4yip | ```\n\nclass Solution:\n def reformat(self, s: str) -> str:\n letters =""\n digits = ""\n for ch in s:\n if \'a\'<= ch <=\'z\ | soham9 | NORMAL | 2020-07-14T02:59:31.838944+00:00 | 2020-07-14T03:03:10.402049+00:00 | 177 | false | ```\n\nclass Solution:\n def reformat(self, s: str) -> str:\n letters =""\n digits = ""\n for ch in s:\n if \'a\'<= ch <=\'z\':\n letters +=ch\n else:\n digits +=ch\n \n if len(digits) == 1:\n return digits\n \n if abs(len(letters)-len(digits)) > 1 or len(letters) == 0:\n return ""\n \n ans = ""\n if len(letters) < len(digits):\n letters,digits = digits,letters\n \n for idx in range(len(letters)):\n ans += letters[idx]\n if idx < len(digits):\n ans += digits[idx]\n \n return ans\n | 1 | 0 | ['Python3'] | 0 |
reformat-the-string | [Java] Concise solution. | java-concise-solution-by-nkallen-kasn | \nclass Solution {\n public String reformat(String s) {\n Queue<Character> q1 = new LinkedList<>(), q2 = new LinkedList<>();\n for(char c : s.t | nkallen | NORMAL | 2020-07-12T04:29:29.770245+00:00 | 2020-07-12T04:29:29.770315+00:00 | 85 | false | ```\nclass Solution {\n public String reformat(String s) {\n Queue<Character> q1 = new LinkedList<>(), q2 = new LinkedList<>();\n for(char c : s.toCharArray()){\n if(Character.isLetter(c)){\n q1.offer(c);\n }else q2.offer(c);\n }\n if(Math.abs(q1.size() - q2.size()) > 1) return "";\n return helper(q1, q2);\n }\n \n private String helper(Queue<Character> q1, Queue<Character> q2){\n if(q1.size() < q2.size()) return helper(q2, q1);\n StringBuilder sb = new StringBuilder();\n while(!q1.isEmpty()){\n sb.append(q1.poll());\n if(!q2.isEmpty()) sb.append(q2.poll());\n }\n return sb.toString();\n }\n}\n``` | 1 | 0 | [] | 0 |
reformat-the-string | Python3 two solutions time O(n), space O(n) and time O(n), space O(1) | python3-two-solutions-time-on-space-on-a-p2ri | 2 lists: time O(n), space O(n)\n\n def reformat(self, s: str) -> str:\n digits, chars = [], []\n for c in s:\n if c.isdigit():\n | dhxia | NORMAL | 2020-06-05T02:15:32.394891+00:00 | 2020-06-05T14:54:13.329783+00:00 | 87 | false | 2 lists: time O(n), space O(n)\n```\n def reformat(self, s: str) -> str:\n digits, chars = [], []\n for c in s:\n if c.isdigit():\n digits.append(c)\n else:\n chars.append(c)\n nD, nC = len(digits), len(chars)\n if -1 <= nD - nC <= 1:\n if nD < nC:\n digits, chars = chars, digits\n ans = []\n while digits:\n ans.append(digits.pop())\n if chars:\n ans.append(chars.pop())\n return "".join(ans)\n else:\n return ""\n```\n2 pointers: time O(n), space O(1)\n```\n def reformat(self, s: str) -> str:\n def moveToNextDigit():\n nonlocal i, n\n while i < n:\n i += 1\n if i == n or s[i].isdigit():\n return \n def moveToNextChar():\n nonlocal j, n\n while j < n:\n j += 1\n if j == n or not s[j].isdigit():\n return \n \n n = len(s)\n i = j = -1\n ans = []\n while True:\n moveToNextDigit()\n if i < n:\n ans.append(s[i])\n else:\n moveToNextChar()\n if j == n:\n return "".join(ans)\n ans.insert(0, s[j])\n moveToNextChar()\n return "".join(ans) if j == n else ""\n \n moveToNextChar()\n if j < n:\n ans.append(s[j])\n else:\n moveToNextDigit()\n return "".join(ans) if i == n else ""\n pass\n``` | 1 | 0 | [] | 0 |
reformat-the-string | C# very ugly solution, please don't judge | c-very-ugly-solution-please-dont-judge-b-zjfa | Using two stacks I can compare the counts and then use the stacks to pop off in the required order\ni once again check near the end to decide if I have to pop a | nikolatesla20 | NORMAL | 2020-05-23T19:09:03.723930+00:00 | 2020-05-23T19:09:03.723983+00:00 | 49 | false | Using two stacks I can compare the counts and then use the stacks to pop off in the required order\ni once again check near the end to decide if I have to pop an extra off or not. That part of the code is not optimized, I probably only need to check once at the end, which stack requires an extra pop\n\n```\npublic class Solution {\n public string Reformat(string s) {\n \n // push to stacks..\n Stack<char> letters = new Stack<char>();\n Stack<char> numbers = new Stack<char>();\n \n foreach(var c in s)\n {\n if (Char.IsLetter(c))\n {\n letters.Push(c);\n }else\n {\n numbers.Push(c);\n }\n }\n \n int check = letters.Count - numbers.Count;\n if (check == 1 || check==-1 || check==0)\n {\n //ok\n }else\n {\n return String.Empty;\n }\n \n \n StringBuilder retvalue = new StringBuilder();\n \n if (numbers.Count > letters.Count)\n {\n \n int counter = letters.Count;\n \n for(int i=0; i<counter;i++)\n {\n retvalue.Append(numbers.Pop());\n retvalue.Append(letters.Pop());\n }\n retvalue.Append(numbers.Pop());\n \n }else if (letters.Count > numbers.Count)\n { \n int counter = numbers.Count;\n for(int i=0; i<counter;i++)\n {\n retvalue.Append(letters.Pop());\n retvalue.Append(numbers.Pop());\n } \n retvalue.Append(letters.Pop());\n }else\n {\n int counter = letters.Count;\n for(int i=0; i<counter;i++)\n {\n retvalue.Append(letters.Pop());\n retvalue.Append(numbers.Pop());\n } \n }\n\n \n return retvalue.ToString();\n }\n}\n``` | 1 | 0 | [] | 0 |
reformat-the-string | straight forward python | straight-forward-python-by-goodfine1210-3r1r | \nclass Solution:\n def reformat(self, s: str) -> str:\n \n alp = []\n num = []\n res = []\n \n for l in s:\n | goodfine1210 | NORMAL | 2020-05-09T23:27:26.695812+00:00 | 2020-05-09T23:28:09.223064+00:00 | 79 | false | ```\nclass Solution:\n def reformat(self, s: str) -> str:\n \n alp = []\n num = []\n res = []\n \n for l in s:\n if l.isalpha():\n alp.append(l)\n\t\t\t\t\n if l.isnumeric():\n num.append(l)\n \n if abs(len(alp) - len(num)) >= 2:\n return \'\'\n \n flag = (len(alp) > len(num))\n \n \n \n for i in range(len(s)):\n if flag:\n res.append(alp.pop())\n\n else:\n res.append(num.pop())\n \n flag = not flag \n \n return \'\'.join(res) \n \n\n\n\n``` | 1 | 0 | [] | 0 |
reformat-the-string | JavaScript Easy Intuitive Soluttion | javascript-easy-intuitive-soluttion-by-d-0jme | The idea is, \n1. Loop over the string and store data in two arrays, one with alphabets, another with numbers.\n2. if the diff of size is > 1, so permutation no | dibyajyoti_ghosal | NORMAL | 2020-05-09T19:32:26.661219+00:00 | 2020-05-09T19:32:26.661261+00:00 | 118 | false | The idea is, \n1. Loop over the string and store data in two arrays, one with alphabets, another with numbers.\n2. if the diff of size is > 1, so permutation not possible.\n3. decide which one is larger array and which one is smaller.\n4. loop over the length of the larger array, push the element in the larger array first and then the smaller array to avoid undefined coming in because of no available element in smaller array.\n```\nvar reformat = function(s) {\n if(s.length <= 1) return s;\n let map = {\n nums: [],\n alp: []\n };\n let res = [];\n for(let i=0; i<s.length; i++ ) {\n if(isNaN(s[i])) map["alp"].push(s[i]);\n else map["nums"].push(s[i]);\n }\n if(Math.abs(map.nums.length - map.alp.length) > 1) return "";\n \n let maxArr = (map.nums.length >= map.alp.length) ? map.nums : map.alp; \n let smallArr = (map.nums.length < map.alp.length) ? map.nums : map.alp;\n\n for(let i=0; i<maxArr.length; i++) {\n maxArr[i] && res.push(maxArr[i]); \n smallArr[i] && res.push(smallArr[i]);\n }\n return res.join("");\n};\n``` | 1 | 0 | [] | 0 |
reformat-the-string | C++ nothing clever 96% Speed, 100% Memory | c-nothing-clever-96-speed-100-memory-by-3f1mc | \nclass Solution {\npublic:\n string reformat(string s) {\n \n //Separate digits and letters\n string digi = "";\n string lett = | adrianlee0118 | NORMAL | 2020-04-26T00:10:52.083596+00:00 | 2020-04-26T00:10:52.083632+00:00 | 100 | false | ```\nclass Solution {\npublic:\n string reformat(string s) {\n \n //Separate digits and letters\n string digi = "";\n string lett = "";\n for (auto& c : s){\n if (isdigit(c)) digi+=c;\n else lett += c;\n }\n \n //If difference in size of digi and letters exceeds 1, an alternating sequence is impossible\n int a = digi.size();\n int b = lett.size();\n if (fabs(a - b) > 1) return "";\n \n //Build the answer string\n string ans = "";\n if (digi.size() < lett.size()) swap(digi,lett); //ensure digi is the larger string\n for (int i = 0; i < lett.size(); i++){ //build section by section: longer string letter, shorter string letter\n ans += digi[i];\n ans += lett[i];\n }\n if (digi.size() > lett.size()) ans += digi[lett.size()]; //add remaining letter in longer string if there is one and return answer\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
divide-intervals-into-minimum-number-of-groups | Min Heap | min-heap-by-votrubac-6q0v | We use a min heap to track the rightmost number of each group.\n\nFirst, we sort the intervals. Then, for each interval, we check if the top of the heap is less | votrubac | NORMAL | 2022-09-11T04:00:49.226267+00:00 | 2022-09-13T05:26:43.251735+00:00 | 13,728 | false | We use a min heap to track the rightmost number of each group.\n\nFirst, we sort the intervals. Then, for each interval, we check if the top of the heap is less than **left**.\n\nIf it is, we can add that interval to an existing group: pop from the heap, and push **right**, updating the rightmost number of that group.\n\nIf not, we need a new group: push **right** into the heap.\n\nIn the end, the size of the heap is the number of groups we need.\n\n**Python 3**\n```python\nclass Solution:\n def minGroups(self, intervals: List[List[int]]) -> int:\n pq = []\n for left, right in sorted(intervals):\n if pq and pq[0] < left:\n heappop(pq)\n heappush(pq, right)\n return len(pq)\n```\n\n**C++**\n```cpp\nint minGroups(vector<vector<int>>& ints) {\n sort(begin(ints), end(ints));\n priority_queue<int, vector<int>, greater<int>> pq;\n for (const auto &i : ints) {\n if (!pq.empty() && pq.top() < i[0])\n pq.pop();\n pq.push(i[1]);\n }\n return pq.size();\n}\n``` | 331 | 3 | ['C', 'Python3'] | 36 |
divide-intervals-into-minimum-number-of-groups | [Java/C++/Python] Meeting Room | javacpython-meeting-room-by-lee215-bzv8 | Intuition\nExactly same as meeting rooms.\n\n\n# Explanation\nAt time point intervals[i][0],\nstart using a meeting room(group).\n\nAt time point intervals[i][1 | lee215 | NORMAL | 2022-09-11T04:02:37.691941+00:00 | 2022-09-11T04:02:37.691985+00:00 | 13,838 | false | # **Intuition**\nExactly same as meeting rooms.\n<br>\n\n# **Explanation**\nAt time point `intervals[i][0]`,\nstart using a meeting room(group).\n\nAt time point `intervals[i][1] + 1`,\nend using a meeting room.\n\nSort all events by time,\nand accumulate the number of room(group) used.\n<br>\n\n# **Complexity**\nTime `O(nlogn)`\nSpace `O(n)`\n<br>\n\n**Java**\n```java\n public int minGroups(int[][] intervals) {\n int res = 0, cur = 0, n = intervals.length, A[][] = new int[n * 2][2];\n for (int i = 0; i < n; ++i) {\n A[i * 2] = new int[]{intervals[i][0], 1};\n A[i * 2 + 1] = new int[]{intervals[i][1] + 1, -1};\n }\n Arrays.sort(A, Comparator.comparingInt(o -> o[0] * 3 + o[1]));\n for (int[] a: A)\n res = Math.max(res, cur += a[1]);\n return res;\n }\n```\n\n**C++**\nUse verctor.\n```cpp\n int minGroups(vector<vector<int>>& intervals) {\n vector<vector<int>> A;\n for (auto& v : intervals) {\n A.push_back({v[0], 1});\n A.push_back({v[1] + 1, -1});\n }\n int res = 0, cur = 0;\n sort(A.begin(), A.end());\n for (auto& v : A)\n res = max(res, cur += v[1]);\n return res;\n }\n```\nUse map\n```cpp\n int minGroups(vector<vector<int>>& intervals) {\n map<int, int> A;\n for (auto& v : intervals)\n A[v[0]]++, A[v[1] + 1]--;\n int res = 0, cur = 0;\n for (auto& v : A)\n res = max(res, cur += v.second);\n return res;\n }\n```\n**Python**\n```py\n def minGroups(self, intervals):\n A = []\n for a,b in intervals:\n A.append([a, 1])\n A.append([b + 1, -1])\n res = cur = 0\n for a, diff in sorted(A):\n cur += diff\n res = max(res, cur)\n return res\n```\n<br>\n\n# More Sweep Line Problems\nHere are some sweep line problems.\nI\'ll make a summary for this method.\nLet me know other related problems or my other related posts.\nGood luck and have fun.\n\n- [253. Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/)\n- [1094. Car Pooling](https://leetcode.com/problems/car-pooling/discuss/317610/JavaC++Python-Meeting-Rooms-III)\n- [1109. Corporate Flight Bookings](https://leetcode.com/problems/corporate-flight-bookings/discuss/328856/JavaC%2B%2BPython-Straight-Forward-Solution)\n<br>\n\n\n# More Interval Problem\nMore similar intervals problems\n- 252. Meeting Rooms\n- [253. Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/)\n- 495. Teemo Attacking\n- 616. Add Bold Tag in String\n- 759. Employee Free Time\n<br>\n | 166 | 3 | ['C', 'Python', 'Java'] | 32 |
divide-intervals-into-minimum-number-of-groups | C++ Easy Solution | c-easy-solution-by-ayush_gupta4-qahh | \n\n\nclass Solution {\npublic:\n int minGroups(vector<vector<int>>& a) {\n int ans=0, i, n=1000011;\n vector<int> A(n, 0); // Taken the Array | ayush_gupta4 | NORMAL | 2022-09-11T06:16:11.752986+00:00 | 2022-09-11T06:38:55.152331+00:00 | 3,956 | false | \n\n```\nclass Solution {\npublic:\n int minGroups(vector<vector<int>>& a) {\n int ans=0, i, n=1000011;\n vector<int> A(n, 0); // Taken the Array of Big Size\n for(auto x: a) {\n A[x[0]]++; \n A[x[1]+1]--;\n }\n for(i=1;i<n-1;i++) A[i] += A[i-1]; // Prefix Sum\n for(auto x: A) ans=max(ans, x); // Take maximum of Prefix Sums\n return ans; // Return Maximum Value\n }\n};\n``` | 91 | 1 | [] | 16 |
divide-intervals-into-minimum-number-of-groups | Beats 100% TC & SC | Simple and Easy to understand | Python | CPP | Java | beats-100-tc-sc-simple-and-easy-to-under-n2is | Intuition\nWe need to group intervals so that no intervals in the same group overlap. By sorting start and end times, we can track how many intervals overlap at | Baslik69 | NORMAL | 2024-10-12T00:10:20.506955+00:00 | 2024-10-12T00:10:20.506976+00:00 | 25,061 | false | # Intuition\nWe need to group intervals so that no intervals in the same group overlap. By sorting start and end times, we can track how many intervals overlap at any point. If a new interval starts after an earlier one ends, we can reuse that group. Otherwise, we need a new group.\n\n# Approach\n1. **Sort start and end times**: Sorting helps track when intervals start and end.\n2. **Two pointers**: \n\n - `start_ptr` iterates through start times.\n - `end_ptr` tracks the earliest end time. If the current interval starts after the earliest end, reuse a group by incrementing `end_ptr`; otherwise, create a new group.\n3. **Result**: The number of active groups after processing all intervals is the minimum number of groups required.\n# Complexity\n- Time complexity:\n$$O(NLogN)$$\n\n- Space complexity:\n$$O(N)$$\n\n# Code\n```python3 []\nclass Solution:\n def minGroups(self, intervals: List[List[int]]) -> int:\n start_times = sorted(i[0] for i in intervals)\n end_times = sorted(i[1] for i in intervals)\n end_ptr, group_count = 0, 0\n\n for start in start_times:\n if start > end_times[end_ptr]:\n end_ptr += 1\n else:\n group_count += 1\n\n return group_count\n\n```\n```cpp []\nclass Solution {\npublic:\n int minGroups(vector<vector<int>>& intervals) {\n vector<int> start_times, end_times;\n\n // Extract start and end times\n for (const auto& interval : intervals) {\n start_times.push_back(interval[0]);\n end_times.push_back(interval[1]);\n }\n\n // Sort start and end times\n sort(start_times.begin(), start_times.end());\n sort(end_times.begin(), end_times.end());\n\n int end_ptr = 0, group_count = 0;\n\n // Traverse through the start times\n for (int start : start_times) {\n if (start > end_times[end_ptr]) {\n end_ptr++;\n } else {\n group_count++;\n }\n }\n\n return group_count;\n }\n};\n```\n```java []\nclass Solution {\n public int minGroups(int[][] intervals) {\n int n = intervals.length;\n int[] start_times = new int[n];\n int[] end_times = new int[n];\n\n // Extract start and end times\n for (int i = 0; i < n; i++) {\n start_times[i] = intervals[i][0];\n end_times[i] = intervals[i][1];\n }\n\n // Sort start and end times\n Arrays.sort(start_times);\n Arrays.sort(end_times);\n\n int end_ptr = 0, group_count = 0;\n\n // Traverse through the start times\n for (int start : start_times) {\n if (start > end_times[end_ptr]) {\n end_ptr++;\n } else {\n group_count++;\n }\n }\n\n return group_count;\n }\n}\n``` | 86 | 0 | ['Array', 'Two Pointers', 'Greedy', 'Sorting', 'Python', 'C++', 'Java', 'Python3'] | 22 |
divide-intervals-into-minimum-number-of-groups | C++ | Line Sweep | Related Problems | c-line-sweep-related-problems-by-kiranpa-gnws | Use Line Sweep\n- Return the maximum element in the entire range.\ncpp\nclass Solution {\npublic:\n int minGroups(vector<vector<int>>& intervals) {\n\n | kiranpalsingh1806 | NORMAL | 2022-09-11T04:00:46.880895+00:00 | 2022-09-11T10:24:44.683885+00:00 | 4,099 | false | - Use Line Sweep\n- Return the maximum element in the entire range.\n```cpp\nclass Solution {\npublic:\n int minGroups(vector<vector<int>>& intervals) {\n\n int line[1000005] = {};\n int maxEle = -1;\n\n for(auto &e : intervals) {\n int start = e[0], end = e[1];\n line[start] += 1;\n line[end + 1] -= 1;\n }\n\n for(int i = 1; i < 1000001; i++) {\n line[i] += line[i - 1];\n maxEle = max(maxEle, line[i]);\n }\n\n return maxEle;\n }\n};\n```\n\n**Line Sweep**\n1. [1854. Maximum Population Year](https://leetcode.com/problems/maximum-population-year/)\n2. [1943. Describe The Painting](https://leetcode.com/problems/describe-the-painting/)\n3. [2381. Shifting Letters II](https://leetcode.com/problems/shifting-letters-ii/)\n4. [218. The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/)\n5. [732. My Calendar III](https://leetcode.com/problems/my-calendar-iii/)\n6. [2251. Number of Flowers in Full Bloom](https://leetcode.com/problems/number-of-flowers-in-full-bloom/)\n7. [1851. Minimum Interval To Include Each Query](https://leetcode.com/problems/minimum-interval-to-include-each-query/) | 76 | 1 | ['C', 'Prefix Sum', 'C++'] | 8 |
divide-intervals-into-minimum-number-of-groups | 🌟 Step-by-Step Guide to Minimizing Interval Groups 🔥💯 | step-by-step-guide-to-minimizing-interva-9ptm | \n\n## \uD83C\uDF1F Access Daily LeetCode Solutions Repo : click here\n\n---\n\n\n\n---\n\n# Intuition\nThe problem asks us to group overlapping intervals such | withaarzoo | NORMAL | 2024-10-12T00:38:08.076352+00:00 | 2024-10-12T00:38:08.076386+00:00 | 6,881 | false | \n\n## \uD83C\uDF1F **Access Daily LeetCode Solutions Repo :** [click here](https://github.com/withaarzoo/LeetCode-Solutions)\n\n---\n\n\n\n---\n\n# Intuition\nThe problem asks us to group overlapping intervals such that no two intervals in the same group overlap. Intuitively, the number of groups will be determined by the maximum number of overlapping intervals at any given time.\n\nIf multiple intervals overlap at a particular point, they must go into different groups. So, the core idea is to calculate the maximum number of overlaps at any time.\n\n---\n\n# Approach\n1. **Sort the intervals** by their start times to process them in chronological order.\n2. Use a **priority queue (min-heap)** to track the end times of the intervals. The heap will help us manage the intervals that are currently active.\n - If the start time of the new interval is greater than the earliest end time in the heap, this means the interval can be placed in an existing group. So, we remove the top of the heap and replace it with the new interval\'s end time.\n - If the start time of the interval is earlier than all end times in the heap, it means we need a new group, and we add the new end time to the heap.\n3. At the end of processing all intervals, the size of the heap represents the number of groups needed, as each element in the heap corresponds to an active group.\n\n---\n\n# Complexity\n- **Time complexity**: \n - Sorting the intervals takes \\(O(n \\log n)\\), where \\(n\\) is the number of intervals.\n - Each heap operation (insert or remove) takes \\(O(\\log n)\\), and since we process each interval, the total complexity is \\(O(n \\log n)\\).\n \n- **Space complexity**: \n - The space complexity is \\(O(n)\\) for storing the intervals and the heap.\n\n---\n\n# Code\n```C++ []\n#include <vector>\n#include <queue>\n#include <algorithm>\nusing namespace std;\n\nclass Solution {\npublic:\n int minGroups(vector<vector<int>>& intervals) {\n sort(intervals.begin(), intervals.end());\n priority_queue<int, vector<int>, greater<int>> pq;\n for (const auto& interval : intervals) {\n int start = interval[0], end = interval[1];\n if (!pq.empty() && pq.top() < start) {\n pq.pop();\n }\n pq.push(end);\n }\n return pq.size();\n }\n};\n\n```\n```Java []\nimport java.util.*;\n\nclass Solution {\n public int minGroups(int[][] intervals) {\n Arrays.sort(intervals, (a, b) -> a[0] - b[0]);\n PriorityQueue<Integer> pq = new PriorityQueue<>();\n for (int[] interval : intervals) {\n int start = interval[0], end = interval[1];\n if (!pq.isEmpty() && pq.peek() < start) {\n pq.poll();\n }\n pq.add(end);\n }\n return pq.size();\n }\n}\n\n```\n```JavaScript []\n/**\n * @param {number[][]} intervals\n * @return {number}\n */\nvar minGroups = function(intervals) {\n const events = [];\n for (const [start, end] of intervals) {\n events.push([start, 1]);\n events.push([end + 1, -1]);\n }\n events.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]);\n let maxGroups = 0, currentGroups = 0;\n for (const [time, type] of events) {\n currentGroups += type;\n maxGroups = Math.max(maxGroups, currentGroups);\n }\n return maxGroups;\n};\n\n```\n```Python []\nimport heapq\n\nclass Solution:\n def minGroups(self, intervals: List[List[int]]) -> int:\n intervals.sort()\n pq = []\n for start, end in intervals:\n if pq and pq[0] < start:\n heapq.heappop(pq)\n heapq.heappush(pq, end)\n return len(pq)\n\n```\n```Go []\nimport (\n "container/heap"\n "sort"\n)\ntype MinHeap []int\nfunc (h MinHeap) Len() int { return len(h) }\nfunc (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }\nfunc (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\nfunc (h *MinHeap) Push(x interface{}) {\n *h = append(*h, x.(int))\n}\nfunc (h *MinHeap) Pop() interface{} {\n old := *h\n n := len(old)\n x := old[n-1]\n *h = old[0 : n-1]\n return x\n}\nfunc minGroups(intervals [][]int) int {\n sort.Slice(intervals, func(i, j int) bool {\n return intervals[i][0] < intervals[j][0]\n })\n pq := &MinHeap{}\n heap.Init(pq)\n for _, interval := range intervals {\n start, end := interval[0], interval[1]\n if pq.Len() > 0 && (*pq)[0] < start {\n heap.Pop(pq)\n }\n heap.Push(pq, end)\n }\n return pq.Len()\n}\n\n```\n\n\n---\n\n# Step-by-Step Detailed Explanation\n\n1. **Sorting the Intervals**: \n - First, we sort the intervals by their start times. This allows us to process them in order and ensures that we always consider earlier intervals first.\n\n2. **Using a Priority Queue**: \n - The min-heap (or priority queue) helps us track the end times of the currently active intervals. The heap ensures that the interval with the earliest end time is always accessible at the top.\n \n3. **Checking Overlaps**: \n - For each interval, if its start time is greater than the smallest end time (top of the heap), we know that this interval doesn\'t overlap with the earliest ending interval, and we can reuse that group. We remove the earliest end time from the heap.\n - Otherwise, if there\'s an overlap, we need to create a new group for this interval. We add its end time to the heap.\n\n4. **Final Count of Groups**: \n - After processing all intervals, the number of active intervals (i.e., the size of the heap) gives us the number of groups required, as each interval in the heap represents an active group.\n\n---\n\n\n | 38 | 0 | ['Array', 'Two Pointers', 'Greedy', 'Sorting', 'Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript'] | 8 |
divide-intervals-into-minimum-number-of-groups | C++ || Simple solution using Min Heap || Detailed Explanation | c-simple-solution-using-min-heap-detaile-2mkp | \nclass Solution {\npublic:\n int minGroups(vector<vector<int>>& intervals) {\n\t\t// Sort intervals based on the start\n sort(intervals.begin(), inte | _Potter_ | NORMAL | 2022-09-11T04:18:09.222190+00:00 | 2022-09-12T05:28:26.667986+00:00 | 3,103 | false | ```\nclass Solution {\npublic:\n int minGroups(vector<vector<int>>& intervals) {\n\t\t// Sort intervals based on the start\n sort(intervals.begin(), intervals.end());\n \n\t\t// Heap stores the ending interval of each group\n priority_queue<int,vector<int>,greater<int>> heap;\n \n int ans = 1;\n\t\theap.push(intervals[0][1]);\n\n for(int i=1; i<intervals.size(); i++){\n\t\t\t// If the current interval merges with the min group, then it should be added in new group \n\t\t\t// No need to check with other group intervals, because it merges with all other groups as we\'re maintaing min heap\n if(intervals[i][0] <= heap.top()){\n heap.push(intervals[i][1]);\n }\n\t\t\t// Curr interval not merging with min group, then update the group interval\n else{\n heap.pop();\n heap.push(intervals[i][1]);\n }\n }\n \n return heap.size();\n }\n};\n```\n```\ncout << "Upvote the solution if you like it !!" << endl;\n``` | 38 | 0 | ['C', 'Heap (Priority Queue)', 'C++'] | 4 |
divide-intervals-into-minimum-number-of-groups | [Java] 🔥🔥37ms 100%🔥🔥 || Meeting Room II || 1 line | java-37ms-100-meeting-room-ii-1-line-by-k5jzw | Exactly the same as 253. Meeting Rooms II\n37ms submission\n# method 1\nI put in neccesary comments hopefully it\'s easy enough to understand, just 1 line core | byegates | NORMAL | 2022-09-12T07:08:27.401828+00:00 | 2022-09-18T08:27:23.137941+00:00 | 1,504 | false | Exactly the same as [253. Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/)\n[37ms submission](https://leetcode.com/submissions/detail/802726465/)\n# method 1\nI put in neccesary comments hopefully it\'s easy enough to understand, just 1 line core logic\n```java\nclass Solution {\n public int minGroups(int[][] mx) {\n int n = mx.length;\n int[] begin = new int[n], end = new int[n];\n for (int i = 0; i < n; i++) {\n begin[i] = mx[i][0];\n end[i] = mx[i][1];\n }\n \n // we sort the start & end time of each meeting separately\n Arrays.sort(begin);\n Arrays.sort(end);\n \n // i traverse all start time of meeting, j traverse end\n // if a meeting starts later than a meeting ends, they can use the same room\n // after we started all meetings (i reached n), how many meetings didn\'t end: n - j\n // that will be all meetings rooms we need\n int j = 0;\n for (int i = 0; i < n; i++) if (begin[i] > end[j]) j++; // 1 line core logic\n \n return n-j;\n }\n}\n```\n\n# method 2, very minor difference\nExactly the same logic, but maybe some find this easier to understand \n```java\n// Exactly the same as 253. Meeting Rooms II\nclass Solution {\n public int minGroups(int[][] mx) {\n int n = mx.length;\n int[] begin = new int[n], end = new int[n];\n for (int i = 0; i < n; i++) {\n begin[i] = mx[i][0];\n end[i] = mx[i][1];\n }\n \n // we sort the start / end time of each meeting separately\n Arrays.sort(begin);\n Arrays.sort(end);\n \n int res = 0; // how many meeting rooms we need\n // i traverse the begin time of each meeting, while j traverse end time of each\n for (int i = 0, j = 0; i < n; i++) {\n if (begin[i] <= end[j]) res++; // when a meeting begins before the current earliest meeting end time, we need a new room for this meeting\n else j++; // when a meeting begins after another meeting ends, we don\'t need a new room, we increase j here to check for next earliest end time (i is increased every loop anyway for new start of meeting)\n }\n \n return res;\n }\n}\n``` | 26 | 0 | ['Greedy', 'Java'] | 3 |
divide-intervals-into-minimum-number-of-groups | 😉Very Easy Clean Code + Full Intution & Thought Process + illustrations | very-easy-clean-code-full-intution-thoug-bro7 | Youtube Explanation\nSoon to be on Channel : https://www.youtube.com/@Intuit_and_Code\nEdited:\nhttps://youtu.be/mqI9LHEBih0?si=oQ_320SzapIjMLg4\n\n> Solution w | Rarma | NORMAL | 2024-10-12T07:23:04.366722+00:00 | 2024-10-12T08:37:49.710708+00:00 | 2,278 | false | # Youtube Explanation\nSoon to be on Channel : https://www.youtube.com/@Intuit_and_Code\nEdited:\nhttps://youtu.be/mqI9LHEBih0?si=oQ_320SzapIjMLg4\n\n> Solution will be Easy, You just need to Go on each slides giving a read\n# Intuition & Approach\n\n\n\n\n\n\n\n\n\n\n\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```cpp []\n// Approach - 01 [ Set ]\nclass Solution {\npublic:\n int minGroups(vector<vector<int>>& inter) {\n int n = inter.size();\n int ans = 0;\n\n // Sort based on interval starting value\n sort(inter.begin(), inter.end());\n\n // UNCOMMENT BELOW TO SEE HOW SORTED VECTOR LOOKS\n // cout<<"intervals = [";\n // int cnt=0;\n // for(auto& val:inter){\n // cout<<"["<<val[0]<<","<<val[1]<<"]";\n // cnt++;\n // if(cnt!=inter.size()){cout<<",";}\n // }\n // cout<<"]";\n\n\n // we used multiset because ending interval \n // might repeats\n multiset<int> st;\n\n for(int i = 0; i < n; i++) {\n int l = inter[i][0];\n int r = inter[i][1];\n\n if(st.empty()) {\n st.insert(r);\n }\n else {\n // // Find the first element greater than or equal to l\n // auto it = st.lower_bound(l);\n \n // Move iterator to the largest value strictly less than l\n if (l > *st.begin()) {\n st.erase(st.begin());\n st.insert(r);\n }\n else{\n st.insert(r);\n }\n\n // Insert the current interval\'s end time\n }\n }\n\n // The size of the set gives the number of groups\n return st.size();\n }\n};\n```\n``` C++ [ ]\n// Approach - 02 [ min-heap ]\nclass Solution {\npublic:\n int minGroups(vector<vector<int>>& inter) {\n int n = inter.size();\n\n // Sort based on interval starting value\n sort(inter.begin(), inter.end());\n\n priority_queue<int, vector<int>, greater<int>> pq;\n\n for(int i = 0; i < n; i++) {\n int l = inter[i][0];\n int r = inter[i][1];\n\n if(pq.empty()){\n pq.push(r);\n }\n else{\n if(pq.top() >= l){\n pq.push(r);\n }\n else{\n pq.pop();\n pq.push(r);\n }\n }\n }\n\n // The size of the set gives the number of groups\n return pq.size();\n }\n};\n```\n``` Java [ ]\nclass Solution {\n public int minGroups(int[][] inter) {\n int n = inter.length;\n\n // Sort based on interval starting value\n Arrays.sort(inter, (a, b) -> Integer.compare(a[0], b[0]));\n\n // Min-Heap to store the end times\n PriorityQueue<Integer> pq = new PriorityQueue<>();\n\n for (int i = 0; i < n; i++) {\n int l = inter[i][0];\n int r = inter[i][1];\n\n if (pq.isEmpty()) {\n pq.add(r);\n } else {\n if (pq.peek() >= l) {\n pq.add(r);\n } else {\n pq.poll();\n pq.add(r);\n }\n }\n }\n\n // The size of the heap gives the number of groups\n return pq.size();\n }\n}\n```\n``` Py [ ]\nclass Solution:\n def minGroups(self, inter):\n inter.sort()\n\n pq = []\n\n for l, r in inter:\n if not pq:\n heapq.heappush(pq, r)\n else:\n if pq[0] >= l:\n heapq.heappush(pq, r)\n else:\n heapq.heappop(pq)\n heapq.heappush(pq, r)\n\n return len(pq)\n``` | 24 | 0 | ['Array', 'Math', 'Two Pointers', 'Greedy', 'Sorting', 'Heap (Priority Queue)', 'Ordered Set', 'C++', 'Java', 'Python3'] | 4 |
divide-intervals-into-minimum-number-of-groups | [Java] Prefix Sum | smart trick with +1 and -1 | java-prefix-sum-smart-trick-with-1-and-1-zmt5 | \nclass Solution {\n public int minGroups(int[][] intervals) {\n int[] count = new int[1000002];\n \n for(int[] in : intervals){\n | a_lone_wolf | NORMAL | 2022-09-11T04:00:39.640217+00:00 | 2022-09-11T04:01:20.811120+00:00 | 1,660 | false | ```\nclass Solution {\n public int minGroups(int[][] intervals) {\n int[] count = new int[1000002];\n \n for(int[] in : intervals){\n count[in[0]]++;\n count[in[1]+1]--;\n }\n \n int max = 0;\n \n for(int i = 1; i < 1000002; i++){\n count[i] += count[i-1];\n max = Math.max(max, count[i]);\n }\n \n return max;\n }\n}\n``` | 21 | 0 | ['Prefix Sum'] | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.