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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
count-sorted-vowel-strings | easy peasy squeasy dp | easy-peasy-squeasy-dp-by-fr1nkenstein-l69n | well the question is entirely based on previous results as like we know 1 vowel will always make only 1 combinaation no matter how many spaces are given, so we | fr1nkenstein | NORMAL | 2022-05-11T05:26:14.181192+00:00 | 2022-05-11T05:26:36.645213+00:00 | 435 | false | well the question is entirely based on previous results as like we know 1 vowel will always make only 1 combinaation no matter how many spaces are given, so we initialize entire dp with 1, now n are given spaces and 5 are number for character we can use (vowels) , further i noticed n character at 1 space gives us n as answere and then merging both of them i saw every answere is sum of previous two \n\'\'\'\nclass Solution {\n public int countVowelStrings(int n) {\n int dp[][]=new int[n][5];\n for(int i=0;i<n;i++)dp[i][0]=1;\n for(int i=0;i<5;i++)dp[0][i]=i+1;\n for(int i=1;i<n;i++){\n for(int j=1;j<5;j++)dp[i][j]=dp[i-1][j]+dp[i][j-1];\n }\n return dp[n-1][4];\n }\n}\n\'\'\' | 5 | 0 | ['Dynamic Programming', 'Java'] | 0 |
count-sorted-vowel-strings | A valid solution (beats 90%), O(1) - no DP | a-valid-solution-beats-90-o1-no-dp-by-da-9voo | Beats 85% in time, and better than 90% in space.\n\nUses an advanced feature called "case-switch" to achive O(1) time & space in only 100 lines of code.\n\npubl | DanWritesCode | NORMAL | 2022-05-11T02:43:31.103022+00:00 | 2022-05-11T02:43:31.103056+00:00 | 325 | false | Beats 85% in time, and better than 90% in space.\n\nUses an advanced feature called "case-switch" to achive O(1) time & space in only 100 lines of code.\n\n```public class Solution {\n public int CountVowelStrings(int n) {\n switch(n) {\n case 1:\n return 5;\n case 2:\n return 15;\n case 3:\n return 35;\n case 4:\n return 70;\n case 5:\n return 126;\n case 6:\n return 210;\n case 7:\n return 330;\n case 8:\n return 495;\n case 9:\n return 715;\n case 10:\n return 1001;\n case 11:\n return 1365;\n case 12:\n return 1820;\n case 13:\n return 2380;\n case 14:\n return 3060;\n case 15:\n return 3876;\n case 16:\n return 4845;\n case 17:\n return 5985;\n case 18:\n return 7315;\n case 19:\n return 8855;\n case 20:\n return 10626;\n case 21:\n return 12650;\n case 22:\n return 14950;\n case 23:\n return 17550;\n case 24:\n return 20475;\n case 25:\n return 23751;\n case 26:\n return 27405;\n case 27:\n return 31465;\n case 28:\n return 35960;\n case 29:\n return 40920;\n case 30:\n return 46376;\n case 31:\n return 52360;\n case 32:\n return 58905;\n case 33:\n return 66045;\n case 34:\n return 73815;\n case 35:\n return 82251;\n case 36:\n return 91390;\n case 37:\n return 101270;\n case 38:\n return 111930;\n case 39:\n return 123410;\n case 40:\n return 135751;\n case 41:\n return 148995;\n case 42:\n return 163185;\n case 43:\n return 178365;\n case 44:\n return 194580;\n case 45:\n return 211876;\n case 46:\n return 230300;\n case 47:\n return 249900;\n case 48:\n return 270725;\n case 49:\n return 292825;\n case 50:\n return 316251;\n }\n return 0;\n }\n}``` | 5 | 2 | [] | 2 |
count-sorted-vowel-strings | C++ || Easy & Simple Code || DP | c-easy-simple-code-dp-by-agrasthnaman-yr9i | \nclass Solution {\npublic:\n int countVowelStrings(int n) {\n vector<int> dp(5, 1);\n for(int i=0; i<n; i++){\n for(int j=1; j<5; j | agrasthnaman | NORMAL | 2022-03-06T21:02:49.043136+00:00 | 2022-03-06T21:02:49.043174+00:00 | 216 | false | ```\nclass Solution {\npublic:\n int countVowelStrings(int n) {\n vector<int> dp(5, 1);\n for(int i=0; i<n; i++){\n for(int j=1; j<5; j++){dp[j] = dp[j-1] + dp[j];}\n }\n return dp[4];\n }\n};\n```\nDo upvote if it helped :) | 5 | 0 | ['Dynamic Programming', 'C'] | 1 |
count-sorted-vowel-strings | Top Down Dp Runtime 1 ms Easy Solution | top-down-dp-runtime-1-ms-easy-solution-b-r4uf | \nclass Solution {\n public int countVowelStrings(int n) {\n \n int [][]dp=new int[5][n+1];\n int i,j;\n \n for(i=0;i<5;i++)\n | aadishjain__ | NORMAL | 2021-10-25T12:32:10.850485+00:00 | 2021-10-25T12:32:10.850525+00:00 | 80 | false | ```\nclass Solution {\n public int countVowelStrings(int n) {\n \n int [][]dp=new int[5][n+1];\n int i,j;\n \n for(i=0;i<5;i++)\n {\n for(j=0;j<=n;j++)\n {\n if(i==0)\n {\n dp[i][j]=1;\n }\n else if(j==0)\n {\n dp[i][j]=1;\n }\n else\n {\n dp[i][j]=dp[i-1][j]+dp[i][j-1];\n }\n }\n }\n return dp[4][n];\n }\n}\n``` | 5 | 1 | [] | 0 |
count-sorted-vowel-strings | 1 line simple solution EXPLAINED | C++ | 100% faster | 1-line-simple-solution-explained-c-100-f-sdv5 | Since the order of alphabets has to lexicographic, the relative positions of all 5 vowels is fixed. The only thing we need to find is the count of occurence of | rajat2001 | NORMAL | 2021-09-30T21:31:57.194099+00:00 | 2021-10-04T16:33:20.341282+00:00 | 131 | false | Since the order of alphabets has to lexicographic, the relative positions of all 5 vowels is fixed. The only thing we need to find is the count of occurence of each vowel. Let us say the counts are x1,x2...,x5\nTherefore, x1+x2+x3+x4+x5 = n (All xi\'s>=0)\nThe number of ways for the above equation is (4+n)C(n) (I\'ve added the general formula below), which on simplifying becomes \n((n+1)*(n+2)*(n+3)*(n+4))/4!\n```\n int countVowelStrings(int n) {\n return ((n+1)*((n+2)*((n+3)*(n+4))/2)/3)/4;\n }\n ```\n The general formula when we have r non-negative integers which add upto an integer n is: (n+r-1)C(r-1)\n\n\t | 5 | 0 | [] | 1 |
count-sorted-vowel-strings | 100% Faster | 100-faster-by-manya24-polx | Liked it? Kindly Upvote \uD83D\uDE0A\u270C\n\nn = 1 -> dp = [ 1 , 2 , 3 , 4 , 5 ]\nn = 2 -> dp = [ 1 , 3 , 6 , 10 , 15 ]\n\nclass Solution {\npublic:\n int c | manya24 | NORMAL | 2021-09-12T19:49:53.761850+00:00 | 2021-09-12T19:49:53.761901+00:00 | 100 | false | ***Liked it? Kindly Upvote*** \uD83D\uDE0A\u270C\n\n**n = 1 -> dp = [ 1 , 2 , 3 , 4 , 5 ]\nn = 2 -> dp = [ 1 , 3 , 6 , 10 , 15 ]**\n```\nclass Solution {\npublic:\n int countVowelStrings(int n)\n {\n vector<int> dp(5 , 1);\n for(int i = 0 ; i < n ; i++)\n {\n for(int j = 1 ; j < 5 ; j++)\n {\n dp[j] = dp[j - 1] + dp[j];\n }\n }\n return dp[4];\n }\n};\n``` | 5 | 0 | [] | 0 |
count-sorted-vowel-strings | Recursion and memoization in python | recursion-and-memoization-in-python-by-d-8x9m | for 1 ; a,e,i,o,u value = 5\nfor 2: \naa, ae, ai, ao, au\n\t\t\t ee, ei, eo, eu\n\t\t\t\t\t ii, io, iu\n\t\t\t\t\t\t oo, ou\n\t\t\t\t\t\t\t | deleted_user | NORMAL | 2021-04-07T10:27:02.848431+00:00 | 2021-04-07T10:39:24.414626+00:00 | 445 | false | for 1 ; a,e,i,o,u value = 5\nfor 2: \naa, ae, ai, ao, au\n\t\t\t ee, ei, eo, eu\n\t\t\t\t\t ii, io, iu\n\t\t\t\t\t\t oo, ou\n\t\t\t\t\t\t\t uu \n\t\t\t\t\t\t\t value = 15\nfor 3: we can add a to all the strings in previous case so 15 will already be there.value will be (n = 2, w = 5) = 15\nlets look at the remaining cases.\n\tnow we need to find values with 4 vowels {e,i,o,u} and need to have 3 lettered strings. i.e (n = 3, vow = 4)\n```\nwe can say f(n = 3, vow = 5) = f(n = 2, vow = 5) # for a case\n\t\t\t\t\t+ f(n = 3, vow = 4) #after removal of a left with vow = 4\n```\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tso we are getting a recursion: \n\t recur(n,w) = recur(n-1, w) //here in the previous case, (2,5)\n\t\t\t\t\t\t + recur(n,w-1) // after using a we are left with {e,i,o,u} so w-1 for that\n```\ndef countVowelStrings(self, n: int) -> int:\n def count(n,vow):\n if vow == 0: return 0\n if n == 0: return 1\n return count(n,vow-1)+count(n-1,vow)\n return count(n,5)\n```\nFor memoization: \njust use a table of size (n+1) * (w+1) and fill it with -1. \nassign values to table and use it whenever its not -1( which means already assigned)\n```\nclass Solution:\n def countVowelStrings(self, n: int) -> int:\n def count(n,vow):\n if vow == 0: \n mem[n][vow] = 0\n return mem[n][vow]\n if n == 0: \n mem[n][vow] = 1\n return mem[n][vow]\n if mem[n][vow]!=-1:\n return mem[n][vow]\n mem[n][vow] = count(n,vow-1)+count(n-1,vow)\n return mem[n][vow]\n mem = [[-1]*6 for i in range(n+1)]\n return count(n,5)\n``` | 5 | 0 | ['Recursion', 'Memoization', 'Python', 'Python3'] | 1 |
count-sorted-vowel-strings | C++ code using recursion and memoization (DP) 100% faster | c-code-using-recursion-and-memoization-d-xo8u | ```\nclass Solution {\npublic:\n int count(int n,int vow,vector>&dp){\n if(vow==0) return dp[n][vow] = 0;\n if(dp[n][vow] != -1)\n | yashgautam113 | NORMAL | 2021-03-08T19:52:23.524609+00:00 | 2021-03-16T11:15:46.366160+00:00 | 509 | false | ```\nclass Solution {\npublic:\n int count(int n,int vow,vector<vector<int>>&dp){\n if(vow==0) return dp[n][vow] = 0;\n if(dp[n][vow] != -1)\n return dp[n][vow];\n if(n==0) return dp[n][vow] = 1;\n dp[n][vow] = count(n,vow - 1,dp) + count(n - 1,vow,dp);\n return dp[n][vow];\n }\n int countVowelStrings(int n) {\n vector<vector<int>>dp(n + 1,vector<int>(6,-1));\n return count(n,5,dp);\n }\n}; | 5 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization', 'C'] | 0 |
count-sorted-vowel-strings | Java | One-line Solution | Math | O(1) and O(1) | java-one-line-solution-math-o1-and-o1-by-1vh4 | Mathematical Explanation:\nThe process we count valid results can be considered as to count combinations when sampling n elements with replacement from the set | orc-dev | NORMAL | 2021-01-12T03:14:38.584361+00:00 | 2021-01-12T03:14:38.584413+00:00 | 310 | false | Mathematical Explanation:\nThe process we count valid results can be considered as **to count combinations when sampling *n* elements with replacement from the set** *S* = { a, e, i, o, u }. Note, we only consider the combinations of the selected elements.\n\nFor example, if n = 3, { a, a, e } and { e, a, a } are considered as the same case, because once the elements are determined, their order is determined by the rule of lexicographically sorting. That\'s why we only need to consider the combination results rather than the permutation.\n\nTo count the combination results of sampling ***n*** elements with replacement from a set S, where |S| = ***m***, we have the formula: ***Result = C(m + n - 1, n)***\n\nFor this question, we have:\nresult = C( |S| + n - 1, n) = C(5 + n - 1, n) = C(n + 4, n) = C(n + 4, 4)\n\nSince the max value of ***n*** is 50, the maximum cumulative product is 54 * 53 * 52 * 51 = 7,590,024, which is within the valid range of **int**, so we can directly write our code as follows:\n\n```\npublic int countVowelStrings(int n) {\n return (n + 4) * (n + 3) * (n + 2) * (n + 1) / 24;\n}\n``` | 5 | 0 | ['Math', 'Java'] | 1 |
count-sorted-vowel-strings | [C++] [DP]- Simple and easy to understand solution | c-dp-simple-and-easy-to-understand-solut-oxqu | \nclass Solution {\npublic:\n \n int countVowelStrings(int n) {\n if(n==0)\n return 0;\n vector<vector<int> > dp(n+1,vector<int> | morning_coder | NORMAL | 2020-11-01T04:39:36.273578+00:00 | 2020-11-01T05:25:58.491750+00:00 | 690 | false | ```\nclass Solution {\npublic:\n \n int countVowelStrings(int n) {\n if(n==0)\n return 0;\n vector<vector<int> > dp(n+1,vector<int> (5,0));\n //dp[i][j]=> sorted string of length i ending at vowel no j(a,e,i,o,u)\n for(int i=0;i<5;i++){\n dp[1][i]=1;\n }\n \n for(int i=2;i<=n;i++){\n for(int j=0;j<5;j++){\n for(int k=0;k<=j;k++)\n dp[i][j]+=dp[i-1][k];\n }\n }\n int ans=0;\n for(int i=0;i<5;i++){\n ans+=dp[n][i];\n }\n return ans;\n }\n};\n``` | 5 | 1 | ['Dynamic Programming', 'C', 'C++'] | 0 |
count-sorted-vowel-strings | [Javascript] Math O(1) | javascript-math-o1-by-alanchanghsnu-3654 | Choose how many vowels will be used (1~5)\n2. Get all sets of possible (k-1) converting points C(n-1, k-1) where k is the number of used vowels.\n\nSince there | alanchanghsnu | NORMAL | 2020-11-01T04:01:35.141014+00:00 | 2020-11-01T16:12:30.318029+00:00 | 692 | false | 1. Choose how many vowels will be used (1~5)\n2. Get all sets of possible `(k-1)` converting points `C(n-1, k-1)` where `k` is the number of used vowels.\n\nSince there are 5 vowels at most, the time complexity is O(1)\n\nFor example, if given n = 6, there are 5 cases:\n\n1. Choose 1 vowel: 5 cases only;\n2. Choose 2 vowels:\nThere are `C(5,2) = 10` types of vowel combinations could be choose. Lets choose `a` and `i` as example.\nOne case is `a-a-a-a-i-i`. From this case, there is **only one converting point to change `a` to `i`**. There are `n-1 = 5` candidates to be converting point, so the total number of possible strings is `C(5,2)*C(5,1)=50`;\n3. Choose 3 vowels:\nTake `a-a-e-i-i-i` as example. We have to **choose 2 positions as converting points** to convert `a->e` and `e->i` respectively. That is, `C(n-1, 2) = C(5, 2) = 10`.\nSo the total possible number in this case is `C(5,3)C(n-1,2) = 100`\n4. Choose 4 vowels: `C(5,4)C(n-1,3) = 50`\n5. Choose 5 vowels: `C(n-1,4) = 5`\n\nSum of the 5 cases = `5+50+100+50+5 = 210`\n\n```\nvar countVowelStrings = function(n) {\n return 5 + 10 * combination(n-1, 1) + 10 * combination(n-1, 2) + 5 * combination(n-1, 3) + combination(n-1, 4);\n};\n\nfunction combination(n, k) {\n if (k === 1)\n return n;\n \n return combination(n-1, k-1)*n/k;\n} | 5 | 0 | ['Math', 'JavaScript'] | 2 |
count-sorted-vowel-strings | DP detailed explanation | dp-detailed-explanation-by-bibasmall-w2f5 | Intuition\n Describe your first thoughts on how to solve this problem. \nLet\'s illustrate this problem with a table. A row reflects the addition of a new lette | bibasmall | NORMAL | 2024-08-22T15:56:18.228399+00:00 | 2024-08-22T19:06:04.916613+00:00 | 177 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLet\'s illustrate this problem with a table. A row reflects the addition of a new letter to a set of possible letters. A column reflects the length of the string. Cells contain the number of strings with the corresponding set of letters and length.\n\nThe number of strings consisting only of the letter "a" is obviously always 1: "a", "aa", "aaa", "aaaa", etc.\n\n\n\nWhen filling in the first column, it is also obvious that with the addition of a new letter, the number of strings increases by 1: ["a"], ["a", "e"], ["a", "e", "i"], etc.\n\n\n\nWhen we think about filling in the "e" in the second column, we would definitely add the result from the cell above, because the cell above holds the result without the current letter. \nSo, we only need to get the number of strings we get when adding the current letter.\nWe can form strings of length 2 with "e" by adding "e" to the strings of length 1: "a" and "e". The number of them is stored to the left of the current cell.\n\n\n\n**For "i" and the 2 column:**\n"a" -> "ai"\n"e" -> "ei"\n"i" -> "ii" from the cell to the left +\n\n"aa", "ae", "ee" from the cell above:\n\n\n\n****For "i" and the 3 column:****\n"aaa", "aae", "aee", "eee" from the cell above +\n\n"aa" -> "aai"\n"ae" -> "aei"\n"ee" -> "eei"\n"ai" -> "aii"\n"ei" -> "eii"\n"ii" -> "iii" from the cell to the left.\n\n\n\n# Approach\nIt\'s easy to notice, that we don\'t need to store the whole table. We only need the current letter value for ```length - 1``` (left cell) and the value of the previous letter for ```length``` (cell above).\nAll we need are 5 variables (actually 4, but lets keep ```a``` for clarity).\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countVowelStrings(int n) {\n int a = 1, e = 2, i = 3, o = 4, u = 5;\n for (; n > 1; --n)\n {\n //above cell + left cell\n e = a + e;\n i = e + i;\n o = i + o;\n u = o + u;\n }\n return u;\n }\n};\n``` | 4 | 0 | ['Dynamic Programming', 'C++'] | 1 |
count-sorted-vowel-strings | One line solution | Math | O(1) | Fastest | one-line-solution-math-o1-fastest-by-bhu-m88r | Intuition\nThis is a simple math problem. Let\'s redefined as "no of ways to select N vowels where each vowel can be repeated."\n Describe your first thoughts o | bhumi_1020 | NORMAL | 2024-08-07T09:51:27.272846+00:00 | 2024-08-07T09:51:27.272872+00:00 | 268 | false | # Intuition\nThis is a simple math problem. Let\'s redefined as "no of ways to select N vowels where each vowel can be repeated."\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe formulae is (n+r-1)C r , where n = 5(number of vowels), r = N.\nSo the formulae is reduced to (4+r)C r, which can be further simplified as:\n(n + 1) * (n + 2) * (n + 3) * (n + 4) / 24 \nny using the properties of nCr.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n\n\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int countVowelStrings(int n) {\n //(n+r-1)C r, r=n(given), n=5(number of vowels)\n //ans would be (n+4)!/((n!)*24)\n return (n + 1) * (n + 2) * (n + 3) * (n + 4) / 24;\n }\n}\n``` | 4 | 0 | ['Math', 'Combinatorics', 'C++', 'Java'] | 0 |
count-sorted-vowel-strings | Pure Mathematical Solution || O(1) || Direct Formula By Observation | pure-mathematical-solution-o1-direct-for-ozi7 | Observations\n /\n Let n = 1: ans = 1 + 1 + 1 + 1 + 1 = 5 \n Let n = 2: ans = 5 + 4 + 3 + 2 + 1 = 15\n Let n = 3: _ _ _ : a a _ -> 5 | abhijeet5000kumar | NORMAL | 2024-02-02T16:47:08.793077+00:00 | 2024-02-02T16:47:47.053099+00:00 | 440 | false | # Observations\n /*\n Let n = 1: ans = 1 + 1 + 1 + 1 + 1 = 5 \n Let n = 2: ans = 5 + 4 + 3 + 2 + 1 = 15\n Let n = 3: _ _ _ : a a _ -> 5 +a e _ -> 4 .....\n a _ _ : 5+4+3+2+1 = 15\n e _ _ : 4+3+2+1 = 10\n ans = 15 + 10 + 6 + 3 + 1 = 35\n \n Let n = 4: _ _ _ _ : \n a _ _ _ : 15+10+6+3+1\n e _ _ _ : 10+6+3+1\n ans = 35 + 20 + 10 + 4 + 1 = 70\n \n ans(u)=1, ans(o)=n, ans(i)=ans(n-2)-ans(n-3)\n ans(a)=ans(n-1), ans(e)=ans(n-1)-ans(n-2)\n\n By solving : ans(a)=(x^4 + 6x^3 + 11x^2 + 6x)/24\n ans(e)=(x^3 + 3x^2 + 2x)/6\n ans(i)=(x^2 + x)/2\n */\n\n\n# Code\n```\nclass Solution {\npublic:\n int countVowelStrings(int n) {\n int four=pow(n,4),three=pow(n,3),two=pow(n,2);\n int a = (four + 6*three + 11*two + 6*n)/24;\n int e = (three + 3*two + 2*n)/6;\n int i = (two + n)/2;\n int o = n;\n int u = 1;\n return (a+e+i+o+u);\n }\n};\n``` | 4 | 0 | ['Math', 'Combinatorics', 'C++'] | 0 |
count-sorted-vowel-strings | DP : Time O(N) and Constant space | dp-time-on-and-constant-space-by-not_act-zzbf | Intuition\n Describe your first thoughts on how to solve this problem. \n \t a e i o u\n n=1 1 1 1 1 1 /a, e, i, o, u\n n=2 5 4 3 | not_active | NORMAL | 2023-10-15T19:32:16.193009+00:00 | 2023-10-15T19:32:16.193037+00:00 | 213 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n \t a e i o u\n n=1 1 1 1 1 1 /a, e, i, o, u\n n=2 5 4 3 2 1 /a-> aa,ae,ai,ao,au | e-> ee,ei,eo,eu | i-> ii,io,iu | o-> oo,ou | u-> uu\n n=3 15 10 6 3 1\n\n Logic: \n in n=3, e will be ((previous \'e\') = 4) + (count of next element \'i\' = 6) \n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int countVowelStrings(int n) {\n int a = 1, e = 1, i = 1, o = 1, u = 1;\n n--;\n while (n--){\n o += u;\n i += o;\n e += i;\n a += e;\n }\n return a + e + i + o + u;\n }\n};\n``` | 4 | 0 | ['C++'] | 1 |
count-sorted-vowel-strings | BEATS 100% in time | 80% in Space complexity | C++ | Precise | beats-100-in-time-80-in-space-complexity-i808 | Code\n\nclass Solution {\n int t[6][51];\n int solve(int i, int n, int k){\n if(k==0){\n return 1;\n }\n if(i== | kr_vishnu | NORMAL | 2023-01-19T14:31:51.986306+00:00 | 2023-01-19T14:31:51.986353+00:00 | 769 | false | # Code\n```\nclass Solution {\n int t[6][51];\n int solve(int i, int n, int k){\n if(k==0){\n return 1;\n }\n if(i==n){\n return 0;\n }\n if(t[i][k] != -1){\n return t[i][k];\n }\n int cnt1=solve(i,n,k-1);\n int cnt2=solve(i+1,n, k);\n return t[i][k]=cnt1+cnt2;\n }\npublic:\n int countVowelStrings(int k) {\n memset(t,-1, sizeof(t));\n return solve(0, 5, k);\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
count-sorted-vowel-strings | O(n) | Runtime: 0 ms, faster than 100.00% | Intuition Explained | on-runtime-0-ms-faster-than-10000-intuit-p6dv | Appraoch 1 \n\nIntution : At First glance it is easy to understand that this is backtracking related question. All we have to do is count all the combination th | prashank123 | NORMAL | 2022-05-11T17:27:26.526081+00:00 | 2022-05-11T18:18:42.537466+00:00 | 577 | false | **Appraoch 1 **\n\nIntution : At First glance it is easy to understand that this is backtracking related question. All we have to do is count all the combination that can generate string of length n and will be of sorted order.\n\nIf we go with backtracking the time complexity will be 2^n. **(OH MY GOD)**. It is too slow. Can we do something better. Lets analyize few test cases to understand the intution may be we can figure out something better.\n\n1. n=1\n\tnumber of possible string will be 5 (a,e,i,o,u)\n\t\n2. n=2\na_ Here we have 5 possible choice for string starting with a\ne_ Here we have 4 possible choice for string starting with e\ni_ Here we have 3 possible choice for string starting with i\no_ Here we have 2 possible choice for string starting with o\nu_ Here we have 1 possible choice for string starting with u\n\nwe have 5 possible choice after a because we need to maintain sorted or so after a we can only place a e i o u ( 5 characters). Similar explaination for string starting with e,i,o,u\n\nTotal String 5+4+3+2+1 =15\n\n3. n=3\n\naa5\nae4\nai3\nao2\nau1\ntotal 15\n\nee4\nei3\neo2\neu1\n\ntotal = 10\n\nii3\nio2\niu1\n\ntotal = 6\n\noo2\nou1\n\ntotal = 3\n\nuu1\ntotal=1\n\nso sum will be\n\n15+10+6+3+1 = 35\n\nSo for n=2\nwe have\n[5,4,3,2,1]\n\nn=3\n[15,10,6,3,1]\n\nDo you see the pattern yet? C\'mon think a bit..\n\nFor array of n=3, element at 0th index is derived from prefix sum of n=2 from 0th to 4th index.\nsimilarly element at 1th index is derived from prefix sum of n=2 from 1 to 4th index and so on forth.\n\nThis is the intituion behind the solution in the code below. If you undestand the intution then try writing the solution on your own. Hope it helps.\n\n\n\n\n\n\n\n```\nclass Solution {\n public int countVowelStrings(int n) {\n \n if(n==1)\n return 5;\n \n if(n==2)\n return 15;\n \n int arr[] = {5,4,3,2,1};\n\n int sum=0;\n \n for(int i=3;i<=n;i++) {\n sum=0;\n\t\t\t//this inner loop will always take constant iteration i.e. 5. So time complexity is O(1) for this\n for(int j=3;j>=0;j--) {\n arr[j]=arr[j]+arr[j+1];\n sum+=arr[j];\n }\n }\n \n return sum+1;\n \n }\n}\n```\n\nT(n) O(5*n) = O(n_\nSpace O(1)\n\n**Approach 2 :**\nIt is still in progress, but i think we can do some mathematical calculation. Once solution is build I will paste it here.\n\n\nPlease upvote if it helps.~~~~!!!!~~~~~~ | 4 | 1 | ['Backtracking', 'Prefix Sum'] | 0 |
count-sorted-vowel-strings | JAVA Backtracking || Worst Case but better understanding | java-backtracking-worst-case-but-better-l45om | \n`class Solution {\n int totalcount = 0;\n public int countVowelStrings(int n) {\n char[]arr = new char[]{\'a\' , \'e\' , \'i\' , \'o\' , \'u\'};\ | banerjeeshibashis01 | NORMAL | 2022-05-11T13:40:47.639253+00:00 | 2022-05-31T09:50:48.398379+00:00 | 55 | false | ```\n`class Solution {\n int totalcount = 0;\n public int countVowelStrings(int n) {\n char[]arr = new char[]{\'a\' , \'e\' , \'i\' , \'o\' , \'u\'};\n dfs(arr , 0 , 0 , n);\n return totalcount;\n }\n public void dfs(char[]arr , int start , int count , int size){\n if(count == size){\n totalcount ++;\n return;\n }\n for(int i = start ; i<5 ; i++){\n count=count+1;\n dfs(arr , i , count , size);\n count=count-1;\n }\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
count-sorted-vowel-strings | [Python] The easiest one with MAD SKILLZ Paint explanation | python-the-easiest-one-with-mad-skillz-p-5b3g | \n\n\tclass Solution:\n\t\tdef countVowelStrings(self, n: int) -> int:\n\t\t\tvowels = deque([5,4,3,2,1])\n\t\t\tsm = temp = sum(vowels)\n\t\t\tfor i in range(1 | Cuno_DNFC | NORMAL | 2022-05-11T11:40:05.944200+00:00 | 2022-05-11T11:40:05.944252+00:00 | 260 | false | \n\n\tclass Solution:\n\t\tdef countVowelStrings(self, n: int) -> int:\n\t\t\tvowels = deque([5,4,3,2,1])\n\t\t\tsm = temp = sum(vowels)\n\t\t\tfor i in range(1, n):\n\t\t\t\tfor _ in range(5):\n\t\t\t\t\tvowels.append(temp)\n\t\t\t\t\ttemp -= vowels.popleft()\n\t\t\t\t\tsm += temp\n\t\t\t\ttemp = sm\n\t\t\treturn vowels[0] | 4 | 0 | ['Queue', 'Python'] | 0 |
count-sorted-vowel-strings | Simple Solution || Recursion || Memoization || Tabular Dynamic Programming | simple-solution-recursion-memoization-ta-m0i0 | Recursion || Memoization || Tabular Dynamic Programming\n\nRecursion:\n\nThought Process:\n1. Pick an element in repeated times.\n2. Don\'t pick the element.\n | sanheen-sethi | NORMAL | 2022-05-11T09:40:23.080902+00:00 | 2022-05-11T15:29:39.338931+00:00 | 331 | false | ### Recursion || Memoization || Tabular Dynamic Programming\n\n**Recursion:**\n\n*Thought Process:*\n1. Pick an element in repeated times.\n2. Don\'t pick the element.\n(Same thought of `unbounded knapsack` or `combination sum I` problem)\n\n> **Void Recursion:**\n\n```\nclass Solution {\npublic:\n \n void calculate(vector<char>& v,int n,int index,int& ans){\n if(n == 0){\n\t\t/* when the string length becomes 0, then we have found the lexicographically \n\t\tsorted string ,increment ans by 1.*/\n\t\t\tans++;\n return;\n }\n if(index >= v.size()) return;\n //pick - after picking element, string length reduce by 1\n calculate(v,n-1,index,ans);\n // not pick - if i didn\'t pick the element, string lenght should be same\n calculate(v,n,index+1,ans);\n }\n \n int countVowelStrings(int n) {\n vector<char> v{\'a\',\'e\',\'i\',\'o\',\'u\'};\n int index = 0; // starting picking elements from index 0\n int ans = 0;\n calculate(v,n,index,ans);\n return ans;\n }\n};\n```\n\n> **Value Returning Recustion:**\n\n```\nclass Solution {\npublic:\n \n int calculate(vector<char>& v,int n,int index){\n if(n == 0){\n return 1;\n }\n if(index >= v.size()) return 0;\n //pick\n int x = calculate(v,n-1,index);\n // not pick\n int y = calculate(v,n,index+1);\n return x+y;\n }\n \n int countVowelStrings(int n) {\n vector<char> v{\'a\',\'e\',\'i\',\'o\',\'u\'};\n int index = 0;\n int ans = 0;\n ans = calculate(v,n,index);\n return ans;\n }\n};\n```\n\n> **Memoization:**\n\n- Now as we found the returning value Recursion functionn, now we will easily memoize it\n- See, which parameters are changing in our recursion function\n\t1. n\n\t2. index\n- So, our memoization vector is 2d vector.\n\n```\nclass Solution {\npublic:\n \n int calculate(vector<char>& v,int n,int index,vector<vector<int>>& memo){\n if(n == 0){\n return 1;\n }\n if(memo[n][index] != -1) return memo[n][index];\n if(index >= v.size()) return 0;\n //pick\n int x = calculate(v,n-1,index,ans,memo);\n // not pick\n int y = calculate(v,n,index+1,ans,memo);\n return memo[n][index] = x+y;\n }\n \n int countVowelStrings(int n) {\n vector<char> v{\'a\',\'e\',\'i\',\'o\',\'u\'};\n int index = 0;\n int ans = 0;\n vector<vector<int>> memo(n+1,vector<int>(6,-1)); // 5 vowels\n ans = calculate(v,n,index,memo);\n return ans;\n }\n};\n```\n\n> **Tabulation**\n\n```\nclass Solution {\npublic:\n \n int countVowelStrings(int n) {\n vector<char> v{\'a\',\'e\',\'i\',\'o\',\'u\'};\n int index = 0;\n int ans = 0;\n vector<vector<int>> dp(n+1,vector<int>(5,0)); // 5 vowels\n \n /* base case fill\n\t\t\t if n == 1 , \n\t\t\t then a,e,i,o,u : number if length 1 string starting with a,e,i,o,u is 1\n */\n\t\tfor(int i = 1; i < 5 ; i++){\n dp[1][i] = 1;\n }\n \n /* for the case of u, if n = 1,2,3,4,... \n\t\t\tthe number of strings generated by u is: u,uu,uuu,uuuu,... \n\t\t\ti.e., 1 one string respectively.\n */\n\t\t\n\t\t/*\n base case fill , if char = u\n\t\t\t- at index 4 char is u in v vector\n */\n\t\t\n\t\tfor(int N = 1; N < n+1 ; N++){\n dp[N][4] = 1;\n }\n \n \n // n->i and index -> j replaceing in recursion memo\n for(int i = 1 ; i < n+1 ; i++){\n\t\t// in increasing order of n.\n for(int j = 3 ; j >=0 ; j--){ \n\t\t\t// in decreasing order of vowels as we dp[i][j] depends on dp[i][j+1];\n dp[i][j] = dp[i-1][j] + dp[i][j+1];\n }\n }\n return accumulate(dp[n].begin(),dp[n].end(),0); // sum of the last vector dp[n] is our ans.\n }\n};\n``` | 4 | 0 | ['Dynamic Programming', 'Backtracking', 'Recursion', 'Memoization'] | 0 |
count-sorted-vowel-strings | Simple Solution || Easy Understanding | simple-solution-easy-understanding-by-12-3s5p | \n//Please do upvote, if you like my solution :)\nclass Solution {\npublic:\n int ans = 0;\n void solve(int n,vector<char> &v,int idx){\n if(n == 0 | 123_tripathi | NORMAL | 2022-05-11T04:08:40.568367+00:00 | 2022-06-01T10:21:35.003653+00:00 | 435 | false | ```\n//Please do upvote, if you like my solution :)\nclass Solution {\npublic:\n int ans = 0;\n void solve(int n,vector<char> &v,int idx){\n if(n == 0){\n ans++;\n return;\n }\n if(idx >= v.size()) return;\n solve(n-1,v,idx);\n solve(n,v,idx+1);\n }\n int countVowelStrings(int n) {\n vector<char> v = {\'a\',\'e\',\'i\',\'o\',\'u\'};\n solve(n,v,0);\n return ans;\n }\n};\n//Please do upvote, if you like my solution :)\n``` | 4 | 0 | ['Backtracking', 'Recursion', 'C', 'C++'] | 1 |
count-sorted-vowel-strings | [C++] Simplest Approach, Pattern recognizing and Efficient O(n). ✅ | c-simplest-approach-pattern-recognizing-dywh7 | Question:\n\nGiven an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.\n\nA str | ShriyanshAgarwal | NORMAL | 2022-05-11T03:42:27.407998+00:00 | 2022-05-11T03:42:27.408054+00:00 | 354 | false | **Question:**\n```\nGiven an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.\n\nA string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet.\n```\n* Before jumping to answering the question, lets understand **lexicographic order**. What it is?\n* The term **Lexicographical order** is a mathematical term known by names: lexical order, lexicographic(al) product, alphabetical order, or **dictionary order**. \n* *You can read more at:[Javatpoint](https://www.javatpoint.com/lexicographical-order-java)*\n* Question is a simple question of permutation and combinations, given there is a length of string given "n" we have to find ho many combinations are possible **only of length n** and by using **only vowels** i.e. a,e,i,o,u. Let\'s understand the same with the given test case.\n\n**Example Test Case:**\n```\nInput: n = 1\nOutput: 5\nExplanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"].\n```\n\n* Now, we need to understand a simple pattern which is being followed in the question:\n```\n\t a e i o u\n n=1 1 1 1 1 1 /a, e, i, o, u\n n=2 5 4 3 2 1 /a-> aa,ae,ai,ao,au | e-> ee,ei,eo,eu | i-> ii,io,iu | o-> oo,ou | u-> uu\n```\n**Solution:**\n* We areu using 5 variables that are given in the question a,e,i,o,u.\n* Here we are adding previous value with the current next element in serial order of of a-e-i-o-u.\n* To understand this go to above example where **n=2**, the while loop will run one time and there will be only **one element** which start with **\'u\'**. For every other element you can see it is **previous+next count.**\n* We will return the function by adding every element(variable) at the end.\n* Time complexity: O(n).\n\n**Solution:**\n```\nclass Solution {\npublic:\n int countVowelStrings(int n) {\n int a=1,e=1,i=1,o=1,u=1;\n while(--n)\n {\n o+=u;\n i+=o;\n e+=i;\n a+=e;\n }\n return a+e+i+o+u;\n }\n};\n```\n**I hope you guys resolved your doubt/query or have learned a new thing, if you really liked the approach / solution / content / explanation don\'t forget to upvote!!. Cheers!!** | 4 | 0 | ['C', 'C++'] | 2 |
count-sorted-vowel-strings | || UNBOUNDED KNAPSACK|| pattern | unbounded-knapsack-pattern-by-badal_jha-tew6 | I observed that we can convert this problem in unbounded knapsack by converting [a,e,i,o,u] into [1,1,1,1,1] . Now it became standard subset sum problem we have | Badal_Jha | NORMAL | 2022-02-03T21:04:11.776570+00:00 | 2022-02-03T21:08:03.523988+00:00 | 110 | false | **I observed that we can convert this problem in unbounded knapsack by converting [a,e,i,o,u] into [1,1,1,1,1] . Now it became standard subset sum problem we have to find number of subset with subset sum=n and we can pick one element more than once**\n\n**this is my first post so please upvote if You like it**\n```\nint countVowelStrings(int n) {\n vector<int>v(5,1);\n int dp[6][n+1];\n \n for(int i=0;i<n+1;i++){\n dp[0][i]=0;\n }\n \n for(int i=0;i<6;i++){\n dp[i][0]=1;\n }\n for(int i=1;i<6;i++){\n for(int j=1;j<n+1;j++){\n \n if(v[i-1]<=j){\n dp[i][j]=dp[i][j-v[i-1]] +dp[i-1][j];\n }\n else dp[i][j]=dp[i-1][j];\n }\n }\n return dp[5][n];\n } \n``` | 4 | 0 | ['Dynamic Programming'] | 0 |
count-sorted-vowel-strings | [C++} Easy to understand Time : O(N) & Space : O(1) | c-easy-to-understand-time-on-space-o1-by-xorf | \nclass Solution\n{\npublic:\n int countVowelStrings(int n)\n {\n int a = 1, e = 1, i = 1, o = 1, u = 1;\n for (int N = 2; N <= n; N++)\n | jayesh2604 | NORMAL | 2021-10-13T07:17:43.282542+00:00 | 2021-10-13T07:17:43.282590+00:00 | 116 | false | ```\nclass Solution\n{\npublic:\n int countVowelStrings(int n)\n {\n int a = 1, e = 1, i = 1, o = 1, u = 1;\n for (int N = 2; N <= n; N++)\n {\n u = a + e + i + o + u;\n o = a + e + i + o;\n i = a + e + i;\n e = a + e;\n a = a;\n }\n return a + e + i + o + u;\n }\n};`\n``` | 4 | 1 | [] | 2 |
count-sorted-vowel-strings | O(1) Time | O(1) Space - Discrete Math | o1-time-o1-space-discrete-math-by-daymon-7e21 | Given that we have a sorted combinations problem, with respect to permutations, we can apply the Combinations With Repetitions formula:\n\n\n\nWhere n is our ob | daymon- | NORMAL | 2021-07-23T19:38:20.583566+00:00 | 2021-07-23T19:38:20.583617+00:00 | 155 | false | Given that we have a sorted combinations problem, with respect to permutations, we can apply the *Combinations With Repetitions* formula:\n\n\n\nWhere n is our object (chars) and k is our repetition (4 vowels)\n\n```\nclass Solution {\n public int countVowelStrings(int n) {\n return ((n + 1) * (n + 2) * (n + 3) * (n + 4))/24;\n }\n}\n```\n | 4 | 0 | [] | 0 |
count-sorted-vowel-strings | Simple and concise C++ solution||With Explanation||100% faster | simple-and-concise-c-solutionwith-explan-q2ry | If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries | anubhavbaner7 | NORMAL | 2021-07-02T07:53:42.557179+00:00 | 2021-07-02T07:53:42.557218+00:00 | 175 | false | **If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries or some improvements please feel free to comment and share your views.**\nTry to observe the pattern.\nNote: Here the element present at each index represents the number of combinations that can be formed by the using the vowels {\'a\',\'e\',\'i\',\'o\',\'u\'}\nfor n=1 dp[]={1,1,1,1,1}\nfor n=2 dp[]={5,4,3,2,1}\nfor n=3 dp[]={15,10,6,3,1}\n```\n int countVowelStrings(int n) {\n vector<int> dp(5,1);\n for(int i=1;i<n;i++)\n {\n for(int j=3;j>=0;j--)\n {\n dp[j]=dp[j+1]+dp[j];\n }\n }\n int res=0;\n for(int i=0;i<5;i++)\n {\n res+=dp[i];\n }\n return res;\n }\n```\n | 4 | 0 | ['Dynamic Programming', 'C', 'C++'] | 0 |
count-sorted-vowel-strings | C++ solution with explanation | Two methods with full explanation | c-solution-with-explanation-two-methods-hqllg | Method 1 - (Using Backtracking)\n\nSolution Idea: \n1. We first create a vector storing all the vowels present in English alphabets.\n2. We the create a functio | baibhabwb007 | NORMAL | 2021-02-02T15:37:32.540158+00:00 | 2021-02-02T18:05:09.386873+00:00 | 131 | false | ***Method 1 - (Using Backtracking)***\n\nSolution Idea: \n1. We first create a vector storing all the vowels present in English alphabets.\n2. We the create a function called *helper* which contains the backtracking algo.\n3. The code has been further commented in each part, for better understanding.\n\n```\nclass Solution {\n \n int count = 0;\n vector<int> word = {\'a\', \'e\', \'i\', \'o\', \'u\'}; //vector containg all the 5 vowels.\n \n void helper(string &s, int n) // string s contains the answer string.\n {\n if(s.size() == n)\n count++; // if the size of s reaches n (given in the problem), we increase count value by 1.\n \n for(int i=0;i<=4;i++)\n { // iterating over all the elements of vector word.\n if(s.size() == 0)\n { // initially, when answer string s in empty, we directly put the letter from word vector, and later perform backtracking.\n\t\t\t\ts.push_back(word[i]);\n\t\t\t\thelper(s, n);\n\t\t\t\ts.pop_back();\n\t\t\t}\n \n\t\t\telse if(s.size()<n && s.back()<=word[i])\n\t\t\t{ // else if size of answer string is greater than 0, but not yet equal to n, and also **the last letter of the string s, is less than the current letter**,\n\t\t\t // we push the current letter in the answer string and do the backtracking as usual.\n\t\t\t\ts.push_back(word[i]);\n\t\t\t\thelper(s, n);\n\t\t\t\ts.pop_back();\n\t\t\t}\n }\n }\npublic:\n int countVowelStrings(int n)\n {\n string s ;\n helper(s, n);\n return count; // returning count value as answer.\n }\n};\n```\n**Time Complexity = O(5^n)**. \nFor every letter out of n, we have 5 possibilities.\n****\n***Method 2 - (Mathematical Pattern)***\n\nSolution Idea: \n Basic idea is to observe a patern amongst the relationship between the given value of n, and the output.\n\nSome observations - \n\t1. For n=1, output is 5.\n\t2. For n=2, output is 15. \n\t By Triangle number formula, putting N=5 in\n\t [ N*(N+1) ]/ [1* 2], we get 15. \n\t3. For n=3, output is 35.\n\t Putting N=5, in \n\t [ N*(N+1)* (N+2) ]/ [ 1* 2* 3 ]\n\t \n\t \nSo, for any value n:\nwe put N=5 in the formula - \n\n\n\n\t\nHence we arrive at our needed expression.\t\n``` \nclass Solution { \npublic:\n int countVowelStrings(int n)\n {\n return (n+1)*(n+2)*(n+3)*(n+4)/24;\n }\n};\n```\n**Time Complexity = O(1)**.\n****\n\nView more solutions [HERE](https://github.com/noob-hu-yaar/Leetcode/tree/master/nandincpp)\n**** | 4 | 0 | [] | 0 |
count-sorted-vowel-strings | The method to obtain the answer of (n + 1)(n + 2)(n + 3)(n + 4) / 24 | the-method-to-obtain-the-answer-of-n-1n-sw3co | As we know, when n = 1, the answer = 5 that is 1 + 1 + 1 + 1 + 1;\nwhen n = 2, the answer = 15 that is 1 + 2 + 3 + 4 + 5\n n = 3, the answer = 35, that | yaody1982 | NORMAL | 2020-12-14T08:11:04.131407+00:00 | 2020-12-14T08:11:04.131464+00:00 | 132 | false | As we know, when n = 1, the answer = 5 that is 1 + 1 + 1 + 1 + 1;\nwhen n = 2, the answer = 15 that is 1 + 2 + 3 + 4 + 5\n n = 3, the answer = 35, that is 1 + 3 + 6 + 10 + 15\n\t\t ....\n\t\t we can set the f(n) = fn(1) + fn(2) + fn(3) + fn(4) + fn(5)\n\t\t fn(1) = 1; \n\t\t fn(2) = 1 + fn-1(2), so fn(2) = 1+1+... + 1 = n;\n\t\t fn(3) = fn-1(3) + fn(2) = n + fn-1(3), so fn(3) = 1 + 2 + ... + n = n(n+1)/2;\n\t\t as usual, fn(4) = 1*2/2 + 2 * 3/2 + 3*4/2 +... + n(n+1)/2 = n(n+1)(n+2)/6;\n\t\t fn(5) = 1*2*3/6 + 2*3*4/6 +...+n(n+1)(n+2)/6 = n(n+1)(n+2)(n+3)/24;\n\t\t so f(n) = fn(1)+fn(2)+fn(3)+fn(4)+fn(5) = 1 + n + n(n+1)/2 + n(n+1)(n+2)/6+n(n+1)(n+2)(n+3)/24 = (n+1)(n+2)(n+3)(n+4)/24\n\t\t | 4 | 0 | [] | 1 |
ambiguous-coordinates | [C++/Java/Python] Solution with Explanation | cjavapython-solution-with-explanation-by-zlto | We can split S to two parts for two coordinates.\nThen we use sub function f to find all possible strings for each coordinate.\n\nIn sub functon f(S)\nif S == " | lee215 | NORMAL | 2018-04-15T03:10:03.850563+00:00 | 2018-10-22T06:48:30.673361+00:00 | 10,557 | false | We can split S to two parts for two coordinates.\nThen we use sub function ```f``` to find all possible strings for each coordinate.\n\n**In sub functon f(S)**\nif S == "": return []\nif S == "0": return [S]\nif S == "0XXX0": return []\nif S == "0XXX": return ["0.XXX"]\nif S == "XXX0": return [S]\nreturn [S, "X.XXX", "XX.XX", "XXX.X"...]\n\nThen we add the product of two lists to result.\n\n**Time complexity**\nO(N^3) with N <= 10\n\nProvement:\n\n\n\nC++:\n```\n vector<string> ambiguousCoordinates(string S) {\n int n = S.size();\n vector<string> res;\n for (int i = 1; i < n - 2; ++i) {\n vector<string> A = f(S.substr(1, i)), B = f(S.substr(i + 1, n - 2 - i));\n for (auto & a : A) for (auto & b : B) res.push_back("(" + a + ", " + b + ")");\n }\n return res;\n }\n vector<string> f(string S) {\n int n = S.size();\n if (n == 0 || (n > 1 && S[0] == \'0\' && S[n - 1] == \'0\')) return {};\n if (n > 1 && S[0] == \'0\') return {"0." + S.substr(1)};\n if (n == 1 || S[n - 1] == \'0\') return {S};\n vector<string> res = {S};\n for (int i = 1; i < n; ++i) res.push_back(S.substr(0, i) + \'.\' + S.substr(i));\n return res;\n }\n```\n**Java:**\n```\n public List<String> ambiguousCoordinates(String S) {\n int n = S.length();\n List<String> res = new ArrayList();\n for (int i = 1; i < n - 2; ++i) {\n List<String> A = f(S.substring(1, i + 1)), B = f(S.substring(i + 1, n - 1));\n for (String a : A) for (String b : B) res.add("(" + a + ", " + b + ")");\n }\n return res;\n }\n public List<String> f(String S) {\n int n = S.length();\n List<String> res = new ArrayList();\n if (n == 0 || (n > 1 && S.charAt(0) == \'0\' && S.charAt(n - 1) == \'0\')) return res;\n if (n > 1 && S.charAt(0) == \'0\') {\n res.add("0." + S.substring(1));\n return res;\n }\n res.add(S);\n if (n == 1 || S.charAt(n - 1) == \'0\') return res;\n for (int i = 1; i < n; ++i) res.add(S.substring(0, i) + \'.\' + S.substring(i));\n return res;\n }\n```\n**Python:**\n```\n def ambiguousCoordinates(self, S):\n S = S[1:-1]\n def f(S):\n if not S or len(S) > 1 and S[0] == S[-1] == \'0\': return []\n if S[-1] == \'0\': return [S]\n if S[0] == \'0\': return [S[0] + \'.\' + S[1:]]\n return [S] + [S[:i] + \'.\' + S[i:] for i in range(1, len(S))]\n return [\'(%s, %s)\' % (a, b) for i in range(len(S)) for a, b in itertools.product(f(S[:i]), f(S[i:]))]\n``` | 156 | 4 | [] | 10 |
ambiguous-coordinates | Really clear Java code | really-clear-java-code-by-wangzi6147-5fuk | \nclass Solution {\n public List<String> ambiguousCoordinates(String S) {\n S = S.substring(1, S.length() - 1);\n List<String> result = new Lin | wangzi6147 | NORMAL | 2018-04-15T03:39:01.574018+00:00 | 2018-08-10T08:30:40.536688+00:00 | 2,939 | false | ```\nclass Solution {\n public List<String> ambiguousCoordinates(String S) {\n S = S.substring(1, S.length() - 1);\n List<String> result = new LinkedList<>();\n for (int i = 1; i < S.length(); i++) {\n List<String> left = allowed(S.substring(0, i));\n List<String> right = allowed(S.substring(i));\n for (String ls : left) {\n for (String rs : right) {\n result.add("(" + ls + ", " + rs + ")");\n }\n }\n }\n return result;\n }\n private List<String> allowed(String s) {\n int l = s.length();\n char[] cs = s.toCharArray();\n List<String> result = new LinkedList<>();\n if (cs[0] == \'0\' && cs[l - 1] == \'0\') { // "0xxxx0" Invalid unless a single "0"\n if (l == 1) {\n result.add("0");\n }\n return result;\n }\n if (cs[0] == \'0\') { // "0xxxxx" The only valid result is "0.xxxxx"\n result.add("0." + s.substring(1));\n return result;\n }\n if (cs[l - 1] == \'0\') { // "xxxxx0" The only valid result is itself\n result.add(s);\n return result;\n }\n result.add(s); // Add itself\n for (int i = 1; i < l; i++) { // "xxxx" -> "x.xxx", "xx.xx", "xxx.x"\n result.add(s.substring(0, i) + \'.\' + s.substring(i));\n }\n return result;\n }\n}\n``` | 60 | 2 | [] | 7 |
ambiguous-coordinates | C++ Clean and Simple Solution Faster Than 96% | c-clean-and-simple-solution-faster-than-vqnum | \nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string s) {\n vector<string> res;\n string s2 = s.substr(1, s.size()-2);\n | yehudisk | NORMAL | 2021-05-13T07:33:31.396723+00:00 | 2021-05-13T07:33:31.396757+00:00 | 2,219 | false | ```\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string s) {\n vector<string> res;\n string s2 = s.substr(1, s.size()-2);\n int n = s2.size();\n \n for (int i = 1; i < n; i++) {\n vector<string> first = getNumbers(s2.substr(0, i));\n vector<string> second = getNumbers(s2.substr(i));\n \n for (int j = 0; j < first.size(); j++) {\n for (int k = 0; k < second.size(); k++) {\n res.push_back("(" + first[j] + ", " + second[k] + ")");\n }\n }\n }\n return res;\n }\n \nprivate:\n vector<string> getNumbers(string num) {\n vector<string> res;\n int n = num.size();\n \n if (n == 1) \n return {num};\n \n if (num[0] != \'0\') \n res.push_back(num);\n \n if (num[0] == \'0\') {\n if (num.back() == \'0\') return {};\n return {"0." + num.substr(1)};\n }\n \n for (int i = 1; i < n; i++) {\n if (num.substr(i).back() == \'0\') continue;\n res.push_back(num.substr(0, i) + "." + num.substr(i));\n }\n \n return res;\n }\n};\n```\n**Like it? please upvote!** | 50 | 6 | ['C'] | 1 |
ambiguous-coordinates | Concise C++ solution with comments | concise-c-solution-with-comments-by-mzch-7yqt | \nvector<string> cases(string &&s) {\n if (s.size() == 1) // single digit\n return {s};\n if (s.front() == \'0\') { // 0xxx\n if (s.back() = | mzchen | NORMAL | 2018-04-15T03:52:48.639367+00:00 | 2018-09-06T00:30:46.019214+00:00 | 1,738 | false | ```\nvector<string> cases(string &&s) {\n if (s.size() == 1) // single digit\n return {s};\n if (s.front() == \'0\') { // 0xxx\n if (s.back() == \'0\') // 0xxx0\n return {};\n return {"0." + s.substr(1)}; // 0xxx9\n }\n if (s.back() == \'0\') // 9xxx0\n return {s};\n vector<string> res{s}; // 9xxx9\n for (int i = 1; i < s.size(); i++)\n res.emplace_back(s.substr(0, i) + "." + s.substr(i));\n return res;\n}\n\nvector<string> ambiguousCoordinates(string S) {\n vector<string> res;\n for (int i = 2; i < S.size() - 1; i++) // position of comma\n for (auto &x : cases(S.substr(1, i - 1)))\n for (auto &y : cases(S.substr(i, S.size() - i - 1)))\n res.emplace_back("(" + x + ", " + y + ")");\n return res;\n}\n``` | 32 | 1 | [] | 2 |
ambiguous-coordinates | [Python] product solution with correct complexity, explained | python-product-solution-with-correct-com-4851 | Let us create function generate(s), which generate all possible candidates for string s: we need to check number without dot and also all possible ways to put d | dbabichev | NORMAL | 2021-05-13T09:18:56.685439+00:00 | 2021-05-13T09:18:56.685467+00:00 | 1,298 | false | Let us create function `generate(s)`, which generate all possible candidates for string `s`: we need to check number without dot and also all possible ways to put dot inside. We need to check the condition `our original representation never had extraneous zeroes`, so we check that if some number starts with `0`, it should be equal to `0`.\n\nThen we split `S` into all possible ways, for each part generate all numbers and then choose all pairs of numbers. \n\n#### Complexity\nThere is `O(n)` ways to split string `S` into two parts. Overall time and space complexity will be `O(n^4)`, for example for string `"(" + "1"*n + ")"`, number of ways will be approximately `n^3/6`, each of them have length `O(n)`.\n\n```python\nclass Solution:\n def ambiguousCoordinates(self, S):\n def generate(s):\n ans = []\n if s == "0" or s[0] != "0": ans.append(s)\n for i in range(1, len(s)):\n if (s[:i] == "0" or s[0] != "0") and s[-1] != "0":\n ans.append(s[:i] + "." + s[i:])\n return ans\n \n n, ans = len(S), []\n for i in range(2, n-1):\n cand_l, cand_r = generate(S[1:i]), generate(S[i:-1]) \n for l, r in product(cand_l, cand_r):\n ans.append("(" + l + ", " + r + ")")\n \n return ans\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 29 | 2 | [] | 2 |
ambiguous-coordinates | JS, Python, Java, C++ | Easy Iterative Solution w/ Explanation | js-python-java-c-easy-iterative-solution-dr9r | (Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\n\n---\n\n#### Idea:\n | sgallivan | NORMAL | 2021-05-13T12:06:12.270810+00:00 | 2021-05-14T00:11:37.859663+00:00 | 1,320 | false | *(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nFor this problem, we have two basic challenges. The first challenge is preventing invalid coordinates. For that, we can define a helper function (**parse**) which will take a string (**str**) and only pass on valid options for another helper (**process**) to handle.\n\nWe can break down the options into three categories:\n - _No decimal_: Any option except one with more than **1** digit and a leading **"0"**.\n - _Decimal after first digit_: Any option with more than **1** digit and no trailing **"0"**.\n - _Decimals throughout_: Any option that doesn\'t start and end with a **"0"**\n\nAfter defining our first helper function, the next thing we should do is iterate through possible comma locations in our input string (**S**) and separate the coordinate pair strings (**xStr, yStr**).\n\nThen we\'ll run into the second challenge, which is to avoid repeating the same processing. If we were to employ a simple nested loop or recursive function to solve this problem, it would end up redoing the same processes many times, since both coordinates can have a decimal.\n\nWhat we actually want is the product of two loops. The basic solution would be to create two arrays and iterate through their combinations, but there\'s really no need to actually build the second array, since we can just as easily process the combinations while we iterate through the second coordinate naturally.\n\nSo we should first build and validate all decimal options for the **xStr** of a given comma position and store the valid possibilities in an array (**xPoss**). Once this is complete we should find each valid decimal option for **yStr**, combine it with each value in **xPoss**, and add the results to our answer array (**ans**) before moving onto the next comma position.\n\nTo aid in this, we can define **process**, which will either store the valid decimal options from **xStr** into **xPoss** or combine valid decimal options from **yStr** with the contents of **xPoss** and store the results in **ans**, depending on which coordinate string we\'re currently on (**xy**).\n\nOnce we finish iterating through all comma positions, we can **return ans**.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **76ms / 42.3MB** (beats 100% / 100%).\n```javascript\nvar ambiguousCoordinates = function(S) {\n let ans = [], xPoss\n const process = (str, xy) => {\n if (xy)\n for (let x of xPoss)\n ans.push(`(${x}, ${str})`)\n else xPoss.push(str)\n }\n const parse = (str, xy) => {\n if (str.length === 1 || str[0] !== "0")\n process(str, xy)\n if (str.length > 1 && str[str.length-1] !== "0")\n process(str.slice(0,1) + "." + str.slice(1), xy)\n if (str.length > 2 && str[0] !== "0" && str[str.length-1] !== "0")\n for (let i = 2; i < str.length; i++)\n process(str.slice(0,i) + "." + str.slice(i), xy)\n }\n for (let i = 2; i < S.length - 1; i++) {\n let strs = [S.slice(1,i), S.slice(i, S.length - 1)]\n xPoss = []\n for (let j = 0; j < 2; j++)\n if (xPoss.length || !j) parse(strs[j], j)\n }\n return ans\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **32ms / 14.1MB** (beats 99% / 92%).\n```python\nclass Solution:\n def ambiguousCoordinates(self, S: str) -> List[str]:\n ans, xPoss = [], []\n def process(st: str, xy: int):\n if xy:\n for x in xPoss:\n ans.append("(" + x + ", " + st + ")")\n else: xPoss.append(st)\n def parse(st: str, xy: int):\n if len(st) == 1 or st[0] != "0":\n process(st, xy)\n if len(st) > 1 and st[-1] != "0":\n process(st[:1] + "." + st[1:], xy)\n if len(st) > 2 and st[0] != "0" and st[-1] != "0":\n for i in range(2, len(st)):\n process(st[:i] + "." + st[i:], xy) \n for i in range(2, len(S)-1):\n strs, xPoss = [S[1:i], S[i:-1]], []\n for j in range(2):\n if xPoss or not j: parse(strs[j], j)\n return ans\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **7ms / 39.5MB** (beats 100% / 91%).\n```java\nclass Solution {\n private List<String> xPoss, ans;\n public List<String> ambiguousCoordinates(String S) {\n ans = new ArrayList<>();\n for (int i = 2; i < S.length() - 1; i++) {\n String[] strs = {S.substring(1,i), S.substring(i, S.length() - 1)};\n xPoss = new ArrayList<>();\n for (int j = 0; j < 2; j++)\n if (xPoss.size() > 0 || j == 0) parse(strs[j], j);\n }\n return ans;\n }\n private void parse(String str, int xy) {\n if (str.length() == 1 || str.charAt(0) != \'0\')\n process(str, xy);\n if (str.length() > 1 && str.charAt(str.length()-1) != \'0\')\n process(str.substring(0,1) + "." + str.substring(1), xy);\n if (str.length() > 2 && str.charAt(0) != \'0\' && str.charAt(str.length()-1) != \'0\')\n for (int i = 2; i < str.length(); i++)\n process(str.substring(0,i) + "." + str.substring(i), xy);\n }\n private void process(String str, int xy) {\n if (xy > 0)\n for (String x : xPoss)\n ans.add("(" + x + ", " + str + ")");\n else xPoss.add(str);\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 9.1MB** (beats 100% / 95%).\n```c++\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string S) {\n for (int i = 2; i < S.size() - 1; i++) {\n string strs[2] = {S.substr(1,i-1), S.substr(i,S.size()-i-1)};\n xPoss.clear();\n for (int j = 0; j < 2; j++)\n if (xPoss.size() || !j) parse(strs[j], j);\n }\n return ans;\n }\nprivate:\n vector<string> ans, xPoss;\n void parse(string str, int xy) {\n if (str.size() == 1 || str.front() != \'0\')\n process(str, xy);\n if (str.size() > 1 && str.back() != \'0\')\n process(str.substr(0,1) + "." + str.substr(1), xy);\n if (str.size() > 2 && str.front() != \'0\' && str.back() != \'0\')\n for (int i = 2; i < str.size(); i++)\n process(str.substr(0,i) + "." + str.substr(i), xy);\n }\n void process(string str, int xy) {\n if (xy)\n for (auto x : xPoss)\n ans.push_back("(" + x + ", " + str + ")");\n else xPoss.push_back(str);\n }\n};\n``` | 27 | 8 | ['C', 'Python', 'Java', 'JavaScript'] | 1 |
ambiguous-coordinates | Ambiguous Coordinates | JS, Python, Java, C++ | Easy Iterative Solution w/ Explanation | ambiguous-coordinates-js-python-java-c-e-2g42 | (Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\n\n---\n\n#### Idea:\n | sgallivan | NORMAL | 2021-05-13T12:07:00.729202+00:00 | 2021-05-14T00:12:39.058808+00:00 | 923 | false | *(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nFor this problem, we have two basic challenges. The first challenge is preventing invalid coordinates. For that, we can define a helper function (**parse**) which will take a string (**str**) and only pass on valid options for another helper (**process**) to handle.\n\nWe can break down the options into three categories:\n - _No decimal_: Any option except one with more than **1** digit and a leading **"0"**.\n - _Decimal after first digit_: Any option with more than **1** digit and no trailing **"0"**.\n - _Decimals throughout_: Any option that doesn\'t start and end with a **"0"**\n\nAfter defining our first helper function, the next thing we should do is iterate through possible comma locations in our input string (**S**) and separate the coordinate pair strings (**xStr, yStr**).\n\nThen we\'ll run into the second challenge, which is to avoid repeating the same processing. If we were to employ a simple nested loop or recursive function to solve this problem, it would end up redoing the same processes many times, since both coordinates can have a decimal.\n\nWhat we actually want is the product of two loops. The basic solution would be to create two arrays and iterate through their combinations, but there\'s really no need to actually build the second array, since we can just as easily process the combinations while we iterate through the second coordinate naturally.\n\nSo we should first build and validate all decimal options for the **xStr** of a given comma position and store the valid possibilities in an array (**xPoss**). Once this is complete we should find each valid decimal option for **yStr**, combine it with each value in **xPoss**, and add the results to our answer array (**ans**) before moving onto the next comma position.\n\nTo aid in this, we can define **process**, which will either store the valid decimal options from **xStr** into **xPoss** or combine valid decimal options from **yStr** with the contents of **xPoss** and store the results in **ans**, depending on which coordinate string we\'re currently on (**xy**).\n\nOnce we finish iterating through all comma positions, we can **return ans**.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **76ms / 42.3MB** (beats 100% / 100%).\n```javascript\nvar ambiguousCoordinates = function(S) {\n let ans = [], xPoss\n const process = (str, xy) => {\n if (xy)\n for (let x of xPoss)\n ans.push(`(${x}, ${str})`)\n else xPoss.push(str)\n }\n const parse = (str, xy) => {\n if (str.length === 1 || str[0] !== "0")\n process(str, xy)\n if (str.length > 1 && str[str.length-1] !== "0")\n process(str.slice(0,1) + "." + str.slice(1), xy)\n if (str.length > 2 && str[0] !== "0" && str[str.length-1] !== "0")\n for (let i = 2; i < str.length; i++)\n process(str.slice(0,i) + "." + str.slice(i), xy)\n }\n for (let i = 2; i < S.length - 1; i++) {\n let strs = [S.slice(1,i), S.slice(i, S.length - 1)]\n xPoss = []\n for (let j = 0; j < 2; j++)\n if (xPoss.length || !j) parse(strs[j], j)\n }\n return ans\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **32ms / 14.1MB** (beats 99% / 92%).\n```python\nclass Solution:\n def ambiguousCoordinates(self, S: str) -> List[str]:\n ans, xPoss = [], []\n def process(st: str, xy: int):\n if xy:\n for x in xPoss:\n ans.append("(" + x + ", " + st + ")")\n else: xPoss.append(st)\n def parse(st: str, xy: int):\n if len(st) == 1 or st[0] != "0":\n process(st, xy)\n if len(st) > 1 and st[-1] != "0":\n process(st[:1] + "." + st[1:], xy)\n if len(st) > 2 and st[0] != "0" and st[-1] != "0":\n for i in range(2, len(st)):\n process(st[:i] + "." + st[i:], xy) \n for i in range(2, len(S)-1):\n strs, xPoss = [S[1:i], S[i:-1]], []\n for j in range(2):\n if xPoss or not j: parse(strs[j], j)\n return ans\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **7ms / 39.5MB** (beats 100% / 91%).\n```java\nclass Solution {\n private List<String> xPoss, ans;\n public List<String> ambiguousCoordinates(String S) {\n ans = new ArrayList<>();\n for (int i = 2; i < S.length() - 1; i++) {\n String[] strs = {S.substring(1,i), S.substring(i, S.length() - 1)};\n xPoss = new ArrayList<>();\n for (int j = 0; j < 2; j++)\n if (xPoss.size() > 0 || j == 0) parse(strs[j], j);\n }\n return ans;\n }\n private void parse(String str, int xy) {\n if (str.length() == 1 || str.charAt(0) != \'0\')\n process(str, xy);\n if (str.length() > 1 && str.charAt(str.length()-1) != \'0\')\n process(str.substring(0,1) + "." + str.substring(1), xy);\n if (str.length() > 2 && str.charAt(0) != \'0\' && str.charAt(str.length()-1) != \'0\')\n for (int i = 2; i < str.length(); i++)\n process(str.substring(0,i) + "." + str.substring(i), xy);\n }\n private void process(String str, int xy) {\n if (xy > 0)\n for (String x : xPoss)\n ans.add("(" + x + ", " + str + ")");\n else xPoss.add(str);\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 9.1MB** (beats 100% / 95%).\n```c++\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string S) {\n for (int i = 2; i < S.size() - 1; i++) {\n string strs[2] = {S.substr(1,i-1), S.substr(i,S.size()-i-1)};\n xPoss.clear();\n for (int j = 0; j < 2; j++)\n if (xPoss.size() || !j) parse(strs[j], j);\n }\n return ans;\n }\nprivate:\n vector<string> ans, xPoss;\n void parse(string str, int xy) {\n if (str.size() == 1 || str.front() != \'0\')\n process(str, xy);\n if (str.size() > 1 && str.back() != \'0\')\n process(str.substr(0,1) + "." + str.substr(1), xy);\n if (str.size() > 2 && str.front() != \'0\' && str.back() != \'0\')\n for (int i = 2; i < str.size(); i++)\n process(str.substr(0,i) + "." + str.substr(i), xy);\n }\n void process(string str, int xy) {\n if (xy)\n for (auto x : xPoss)\n ans.push_back("(" + x + ", " + str + ")");\n else xPoss.push_back(str);\n }\n};\n``` | 23 | 9 | [] | 0 |
ambiguous-coordinates | [Python3] valid numbers | python3-valid-numbers-by-ye15-4zr7 | Algo\nThe key is to deal with extraneous zeros. Below rule gives the what\'s required\n1) if a string has length 1, return it;\n2) if a string with length large | ye15 | NORMAL | 2020-11-13T20:39:43.531125+00:00 | 2021-05-13T16:01:51.253894+00:00 | 831 | false | Algo\nThe key is to deal with extraneous zeros. Below rule gives the what\'s required\n1) if a string has length 1, return it;\n2) if a string with length larger than 1 and starts and ends with 0, it cannot contain valid number;\n3) if a string starts with 0, return `0.xxx`;\n4) if a string ends with 0, return `xxx0`;\n5) otherwise, put decimal point in the `n-1` places. \n\nImplementation \n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s.strip("(").strip(")")\n \n def fn(s): \n """Return valid numbers from s."""\n if len(s) == 1: return [s]\n if s.startswith("0") and s.endswith("0"): return []\n if s.startswith("0"): return [s[:1] + "." + s[1:]]\n if s.endswith("0"): return [s]\n return [s[:i] + "." + s[i:] for i in range(1, len(s))] + [s]\n \n ans = []\n for i in range(1, len(s)): \n for x in fn(s[:i]):\n for y in fn(s[i:]): \n ans.append(f"({x}, {y})")\n return ans \n``` | 14 | 0 | ['Python3'] | 2 |
ambiguous-coordinates | C++ modular code with explanation | c-modular-code-with-explanation-by-ohmah-zv6i | The logic is quite simple for this problem. You have to break the strings, at all possible points. Then you have to again break all the formed substrings, by pl | ohmahgawd | NORMAL | 2020-04-27T11:08:51.692228+00:00 | 2020-05-30T11:06:48.301331+00:00 | 748 | false | The logic is quite simple for this problem. You have to break the strings, at all possible points. Then you have to again break all the formed substrings, by placing dots in between the substrings, and following the `0` rules.\n\nExample - `(1234)`\n\nAfter removing the brackets, we get `s = 1234`. If you break the string at all points, the substrings you get are-\n\n`1 234` -> `1 234`, `1 2.34`, `1 23.4`\n`12 34` -> `12 34`, `12 3.4`, `1.2 34`, `1.2 3.4`\n`123 4` -> `123 4`, `1.23 4`, `12.3 4`\n\nAs you can see I broke the substrings again to insert decimals. Of course you can\'t have something like `1.` or `0001` or `1.00`. For that I use a `check function`.\n\nAs you can see after breaking the string at a particular point, I get two substrings `s1` and `s2`. Then I break both of them into `first` and `second`. `first` represents the part before the decimal and `second` is the part after that.\n\nFor `first`, if it\'s length is greater than `1`, then first digit can\'t be `0`. For example `0.xx` or `0` is valid, but something like `01.xx` or `000` is not acceptable. \nSimilarly, for `second`, the last digit cant be `0`. For example `xx.0` or `xx.30` is not valid.\n\nThe reset is simple. I take 2 vectors `res1` (for storing the first coordinates) and `res2` (for storing the second coordinates), and combine them into the final vector.\n\n```\nclass Solution {\npublic:\n\t// issecword denotes if it is the second word (the part after the decimal)\n bool check(string s, bool issecword)\n {\n int n=s.length();\n\t\t// Logic explained above\n if(issecword){\n if(n>0 && s[n-1]==\'0\') return false;\n }\n else{\n if(n>1 && s[0]==\'0\') return false;\n }\n return true;\n }\n\n vector<string> ambiguousCoordinates(string S) {\n vector<string> res;\n S=S.substr(1,S.length()-2); // Remove the brackets\n int n=S.length();\n\n for(int i=1;i<n;i++){\n string s1=S.substr(0,i);\n string s2=S.substr(i);\n vector<string> res1, res2;\n\t\t\t\n\t\t\t// The full string without any decimal point can also be a coordinate.\n\t\t\t// But \'01\' or \'001\' is not possible.\n if(check(s1, false)) res1.push_back(s1);\n if(check(s2, false)) res2.push_back(s2);\n\t\t\t\n\t\t\t// First co-ordinate\n for(int j=1;j<s1.length();j++){\n string first=s1.substr(0,j);\n string second=s1.substr(j);\n if(check(first, false) && check(second, true)) res1.push_back(first+"."+second);\n }\n\t\t\t\n\t\t\t// Second co-ordinate\n for(int j=1;j<s2.length();j++){\n string first=s2.substr(0,j);\n string second=s2.substr(j);\n if(check(first, false) && check(second, true)) res2.push_back(first+"."+second);\n }\n\t\t\t\n\t\t\t// Combine all the results\n for(auto left:res1){\n for(auto right:res2){\n res.push_back("(" + left + ", "+ right + ")");\n }\n }\n }\n return res;\n }\n};\n```\n\n*Time Complexity* - `O(n^4)` (Because `substr` function is `O(n)` worst case)\n*Space Compexity* - `O(n)` | 11 | 0 | ['String', 'C++'] | 1 |
ambiguous-coordinates | Rust: 0-4ms, 100% Runtime - Iterative Solution | rust-0-4ms-100-runtime-iterative-solutio-iuz9 | rust\nimpl Solution {\n pub fn ambiguous_coordinates(s: String) -> Vec<String> {\n let s = &s.as_bytes()[1..s.len() - 1]; // ignore the parenthesis ar | seandewar | NORMAL | 2021-05-13T08:49:17.860628+00:00 | 2021-05-13T09:35:44.283585+00:00 | 248 | false | ```rust\nimpl Solution {\n pub fn ambiguous_coordinates(s: String) -> Vec<String> {\n let s = &s.as_bytes()[1..s.len() - 1]; // ignore the parenthesis around the coords\n (1..s.len()).fold(vec![], |mut acc, commai| {\n let (x, y) = s.split_at(commai);\n (0..x.len())\n .filter_map(|doti| Self::make_coord(x, doti))\n .for_each(|x| {\n (0..y.len())\n .filter_map(|doti| Self::make_coord(y, doti))\n .for_each(|y| acc.push(format!("({}, {})", x, y)))\n });\n acc\n })\n }\n\n fn make_coord(s: &[u8], doti: usize) -> Option<String> {\n if (s.len() == 1 || doti == 1 || s[0] != b\'0\') && (doti == 0 || s[s.len() - 1] != b\'0\') {\n let (l, r) = s.split_at(doti);\n let l = unsafe { String::from_utf8_unchecked(l.into()) }; // these are safe, as s is\n let r = unsafe { String::from_utf8_unchecked(r.into()) }; // always valid ASCII\n Some(format!("{}{}{}", l, if l.is_empty() { "" } else { "." }, r))\n } else {\n None\n }\n }\n}\n``` | 6 | 1 | ['Iterator', 'Rust'] | 0 |
ambiguous-coordinates | Kotlin best Soltuion | like | kotlin-best-soltuion-like-by-progp-lgeh | \n# Code\n\nclass Solution {\n private fun leadingZeros(v: String): Int {\n var leadingZeros = 0\n while(leadingZeros < v.length && v[leadingZe | progp | NORMAL | 2023-12-10T07:43:30.513285+00:00 | 2023-12-10T07:43:30.513316+00:00 | 50 | false | \n# Code\n```\nclass Solution {\n private fun leadingZeros(v: String): Int {\n var leadingZeros = 0\n while(leadingZeros < v.length && v[leadingZeros] == \'0\') leadingZeros++\n return leadingZeros\n }\n private fun tailingZeros(v: String): Int {\n var tailingZeros = 0\n while(tailingZeros < v.length && v[v.lastIndex - tailingZeros] == \'0\') tailingZeros++\n return tailingZeros\n }\n private fun allValuesOf(n: String): List<String> {\n val values = mutableListOf<String>()\n for(decimalPointIndex in 1 .. n.length) {\n val first = n.substring(0, decimalPointIndex)\n val fl0 = leadingZeros(first)\n if(fl0 >= 2 || fl0 != 0 && first.length != 1) continue\n values += if(decimalPointIndex != n.length) {\n val second = n.substring(decimalPointIndex)\n if(tailingZeros(second) != 0) continue\n "$first.$second"\n } else first\n }\n return values\n }\n fun ambiguousCoordinates(s: String): List<String> {\n val result = mutableListOf<String>()\n for(breakpoint in 2 .. s.lastIndex - 1) {\n val firstValues = allValuesOf(s.substring(1, breakpoint))\n val secondValues = allValuesOf(s.substring(breakpoint, s.lastIndex))\n\n for(first in firstValues)\n for(second in secondValues)\n result += "($first, $second)"\n }\n return result\n }\n}\n``` | 4 | 0 | ['Kotlin'] | 0 |
ambiguous-coordinates | Java Simple and easy to understand solution, 8 ms, faster than 79.79%, clean code with comments | java-simple-and-easy-to-understand-solut-ffm1 | PLEASE UPVOTE IF YOU LIKE THIS SOLUTION\n\n\n\nclass Solution {\n public List<String> ambiguousCoordinates(String s) {\n \n String digits = s.s | satyaDcoder | NORMAL | 2021-05-14T03:58:12.691001+00:00 | 2021-05-14T03:58:12.691038+00:00 | 478 | false | **PLEASE UPVOTE IF YOU LIKE THIS SOLUTION**\n\n\n```\nclass Solution {\n public List<String> ambiguousCoordinates(String s) {\n \n String digits = s.substring(1, s.length() - 1);\n \n List<String> result = new ArrayList();\n if(digits.length() < 2) return result;\n \n \n for(int i = 1; i < digits.length(); i++){\n //split the digits in 2 parts\n String left = digits.substring(0, i);\n String right = digits.substring(i);\n \n //check any of part contains only zeroes \n if((left.length() > 1 && Long.valueOf(left) == 0) || (right.length() > 1 && Long.valueOf(right) == 0)) continue;\n \n \n List<String> leftCoordinates = getValidCoordinates(left);\n if(leftCoordinates.size() == 0) continue;\n \n List<String> rightCoordinates = getValidCoordinates(right);\n if(rightCoordinates.size() == 0) continue;\n \n \n for(String leftCor : leftCoordinates){\n for(String rightCor : rightCoordinates){\n //concatenate right and left coordinate\n StringBuilder sb = new StringBuilder();\n sb\n .append(\'(\')\n .append(leftCor)\n .append(", ")\n .append(rightCor)\n .append(\')\');\n //String coordinate = "(" + leftCor + ", " + rightCor + ")";\n //result.add(coordinate);\n \n result.add(sb.toString());\n }\n }\n \n }\n \n \n \n return result;\n }\n \n private List<String> getValidCoordinates(String str){\n \n List<String> result = new ArrayList();\n \n int n = str.length();\n \n if(n == 1) {\n result.add(str);\n return result;\n }\n \n if(str.charAt(0) == \'0\'){\n if(str.charAt(n - 1) == \'0\'){\n return result;\n }\n \n String coordinate = "0." + str.substring(1); \n result.add(coordinate);\n return result;\n }\n \n if(str.charAt(n - 1) == \'0\'){\n result.add(str);\n return result;\n }\n \n \n for(int i = 1; i < n; i++){\n String coordinate = str.substring(0, i) + "." + str.substring(i); \n result.add(coordinate);\n }\n result.add(str);\n \n return result;\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
ambiguous-coordinates | PYTHON || Well-explained || 97.33% faster || Easy-understanding || | python-well-explained-9733-faster-easy-u-9uka | Idea :\nSplit the string into left and right , then create the possible string seperately , then merge .\n\n When there is only one letter in the string , direc | abhi9Rai | NORMAL | 2021-05-13T10:12:10.851221+00:00 | 2021-05-13T10:12:10.851250+00:00 | 265 | false | ## **Idea :**\nSplit the string into left and right , then create the possible string seperately , then merge .\n\n* When there is only one letter in the string , directly return itself.\n* when the first and last letter is \'0\', then it\'s impossible to create a valid string, return []\n* when the first letter is \'0\', then we only have one choice : \'0.xxxx\'\n* when the last letter is \'0\', then we only have one choice , the string itself.\n* all other , we can put \'.\' between any two letters.\n\n\'\'\'\n\n\tclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n \n def create(num):\n l=len(num)\n if l==1:\n return [num]\n if num[0]=="0" and num[-1]=="0":\n return []\n if num[0]=="0":\n return ["0."+num[1:]]\n if num[-1]=="0":\n return [num]\n local=[num]\n for i in range(1,len(num)):\n local.append(num[:i]+"."+num[i:])\n return local\n \n s=s[1:-1]\n n=len(s)\n res=[]\n for i in range(1,n):\n left = create(s[:i])\n right= create(s[i:])\n if not left or not right:\n continue\n for l in left:\n for r in right:\n res.append(f\'({l}, {r})\')\n return res\n\nThank You!!\nIf you dont get it , feel free to ask. | 3 | 1 | ['Math', 'Python'] | 2 |
ambiguous-coordinates | Modular programming easy to read C++ | modular-programming-easy-to-read-c-by-ic-3vwf | \nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string s) {\n s = s.substr(1, s.length() - 2);\n vector<string> result;\n | icfy | NORMAL | 2021-05-13T07:54:24.608843+00:00 | 2021-05-13T07:54:24.608887+00:00 | 209 | false | ```\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string s) {\n s = s.substr(1, s.length() - 2);\n vector<string> result;\n for (int i = 1; i < s.length(); i++)\n {\n string str1 = s.substr(0, i), str2 = s.substr(i);\n vector<string> res1 = genValid(str1), res2 = genValid(str2);\n\n for (auto& s1 : res1)\n for (auto& s2 : res2)\n genResult(s1, s2, result);\n }\n \n return result;\n }\n \n vector<string> genValid(string& str)\n {\n vector<string> res;\n if (valid(str))\n res.push_back(str);\n \n for (int i = 1; i < str.length(); i++)\n {\n string cur = str.substr(0, i) + "." + str.substr(i);\n if (valid(cur))\n res.emplace_back(cur);\n }\n \n return res;\n }\n \n bool valid(string& str)\n {\n if (str.length() > 1 && str[0] == \'0\' && str[1] != \'.\')\n return false;\n\n if (str.back() == \'0\')\n {\n for (int i = str.length() - 1; i >= 0; i--)\n if (str[i] == \'.\')\n return false;\n }\n \n return true;\n }\n \n void genResult(string& str1, string& str2, vector<string>& result)\n {\n result.emplace_back("(" + str1 + ", " + str2 + ")");\n }\n};\n``` | 3 | 1 | [] | 1 |
ambiguous-coordinates | [Python] Generate. Beats 94% runtime and 91% memory | python-generate-beats-94-runtime-and-91-5xp7k | For a string slice, we generate a list of numbers with following rules:\n1. If the slice is \'0\', then return [\'0\']\n2. If the slice starts and ends with \'0 | watashij | NORMAL | 2021-10-09T19:26:21.605541+00:00 | 2021-10-09T19:26:21.605568+00:00 | 152 | false | For a string slice, we generate a list of numbers with following rules:\n1. If the slice is `\'0\'`, then return `[\'0\']`\n2. If the slice starts and ends with `\'0\'`, we generate nothing. Because we cannot have `0.****0`\n3. If the slice starts with `\'0\'`, then the only number we generate is `0.****`\n4. If the slice does not start with `\'0\'`, but ends with `\'0\'`, which means we can only generate `*****0` without decimal point. Otherwise, we\'d end up with `***.***0`\n5. If the slice does not start with or end with `\'0\'`, then we can generate lots of numbers by inserting the decimal points at any position. For example, using `ABCD` as a base, then we can generate `A.BCD`, `AB.CD`, `ABC.D`.\n```python\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s[1:-1] # remove parenthesis\n def generateNumbers(start, end):\n if s[start] == \'0\': \n if end == start: return [\'0\'] # rule 1\n elif s[end] == \'0\': return [] # rule 2\n else: return [f\'{s[start]}.{s[start+1:end+1]}\'] # rule 3\n base = s[start:end+1]\n res = [base]\n if s[end] != \'0\': # rule 4\n for i in range(1, len(base)): # rule 5\n res.append(f\'{base[:i]}.{base[i:]}\')\n return res\n size = len(s)\n res = []\n for split in range(1, size):\n for first in generateNumbers(0, split - 1):\n for second in generateNumbers(split, size - 1):\n res.append(f\'({first}, {second})\')\n return res\n \n``` | 2 | 0 | [] | 0 |
ambiguous-coordinates | Java | Simple split and apply dots approach | Beats 80% | With explaination | java-simple-split-and-apply-dots-approac-1vjf | Key Intuition: \n1. Split the string up in 2 parts in all possible ways. \n2. Now add dots at various possible places in each split part. Remember to skip insta | towr | NORMAL | 2021-05-13T16:57:51.792713+00:00 | 2021-05-13T16:57:51.792761+00:00 | 256 | false | Key Intuition: \n1. Split the string up in 2 parts in all possible ways. \n2. Now add dots at various possible places in each split part. Remember to skip instances where pre dot part has leading zeros and post dot part has trailing zeros. Also do not forget to include the complete string itself without the dot in case it has no leading zeros. \n3. Find the cross product of list of strings obtained by putting the dot at various places in the left (xcord) and right (ycord) coordinates.\n4. Return this list of cross products of possible string combinations.\n```\n/*\nKey Intuition: \n1. Split the string up in 2 parts in all possible ways. \n2. Now add dots at various possible places in each split part. Remember to skip instances where pre dot part has leading zeros and post dot part has trailing zeros. Also do not forget to include the complete string itself without the dow in case it has no leading zeros. \n3. Find the cross product of list of strings obtained by putting the dot at various places in the left (xcord) and right (ycord) coordinates.\n4. Return this list of cross products of possible string combinations.\n\n*/\nclass Solution {\n public List<String> ambiguousCoordinates(String s) {\n List<String> result = new ArrayList<>();\n \n //Split the string up in 2 parts in all possible ways. \n List<String[]> list = split(s.substring(1, s.length() - 1));\n\n for(String[] split : list) {\n \n //Now add dots at various possible places in each split part. Remember to skip instances where pre dot part has leading zeros and post dot part has trailing zeros. Also do not forget to include the complete string itself without the dot in case it has no leading zeros.\n List<String> xcords = dot(split[0]);\n List<String> ycords = dot(split[1]);\n\t\t\t\n\t\t\t//Find the cross product of list of strings obtained by putting the dot at various places in the left (xcord) and right (ycord) coordinates.\n for(String xcord : xcords) {\n for(String ycord : ycords) {\n result.add("(" + xcord + ", " + ycord + ")");\n }\n }\n }\n return result;\n }\n \n //Split the string up in 2 parts in all possible ways. \n private List<String[]> split(String s) {\n List<String[]> list = new ArrayList<>();\n for(int i = 1; i < s.length(); i++) {\n String[] splits = new String[2];\n splits[0] = s.substring(0, i);\n splits[1] = s.substring(i);\n list.add(splits);\n }\n return list;\n }\n \n private List<String> dot(String s) {\n \n List<String> list = new ArrayList<>();\n \n // do not forget to include the complete string itself without the dow in case it has no leading zeros.\n if(!s.startsWith("0") || s.length() == 1) {\n list.add(s);\n }\n \n if(s.length() == 1) {\n return list;\n }\n \n //Now add dots at various possible places in each split part.\n for(int i = 1; i < s.length(); i++) {\n \n //Remember to skip instances where pre dot part has leading zeros and post dot part has trailing zeros\n String preDot = s.substring(0, i);\n if(preDot.startsWith("0") && preDot.length() > 1) {\n continue;\n }\n String postDot = s.substring(i);\n if(postDot.endsWith("0")) {\n continue;\n }\n list.add(preDot + "." + postDot);\n }\n return list;\n }\n}\n```\n\n**Please upvote if this helped** | 2 | 0 | [] | 2 |
ambiguous-coordinates | C++ Solution || 95% faster | c-solution-95-faster-by-kannu_priya-oysv | \nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string s) {\n int n = s.size();\n vector<string>ans;\n for(int i = 1; | kannu_priya | NORMAL | 2021-05-13T16:35:19.225726+00:00 | 2021-06-04T16:57:38.259297+00:00 | 201 | false | ```\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string s) {\n int n = s.size();\n vector<string>ans;\n for(int i = 1; i < n-2; i++){\n vector<string>A = helper(s.substr(1, i));\n vector<string>B = helper(s.substr(i+1, n-2-i));\n for(auto &a : A)\n for(auto &b : B)\n ans.push_back("(" + a + ", " + b + ")");\n }\n return ans;\n }\n vector<string>helper(string s){\n int n = s.size();\n if(n == 0 || (n > 1 && s[0] == \'0\' && s[n-1] == \'0\')) return {}; //Null string or 0xxx0 \n if(n > 1 && s[0] == \'0\') return {"0." + s.substr(1)}; //0xxx9\n if(n == 1 || s[n-1] == \'0\') return {s}; //single digit or 9xxx0\n \n //9xxx9\n vector<string>ans = {s};\n for(int i = 1; i < n; i++)\n ans.push_back(s.substr(0,i) + \'.\' + s.substr(i));\n return ans; \n }\n};\n``` | 2 | 1 | ['C', 'C++'] | 0 |
ambiguous-coordinates | Explained Algorithm | C++ clean code | explained-algorithm-c-clean-code-by-morn-m2n0 | Intuition:\n1. Need to divide string in two halves and place decimal properly in each half.\n2. Broke the string in two halves and made valid combination list o | morning_coder | NORMAL | 2021-05-13T10:04:24.663834+00:00 | 2021-05-13T11:28:58.192356+00:00 | 200 | false | **Intuition:**\n1. Need to divide string in two halves and place decimal properly in each half.\n2. Broke the string in two halves and made valid combination list of each half. \n3. Received two list from left half and right half - assuming size a and b respectively\n4. Now simple make (a* b) combinations of all elements present in two lists.\n\nWhere to place decimal :\n1. [0XXXX0] -> {}\n2. [0XXXXX] -> {0.XXXX}\n3. [XXXXX0] -> {XXXXX0}\n4. [XXXX] -> [XXXX]+[X.XXX]+[XX.XX]+[XXX.X] \n\n```\nclass Solution {\npublic:\n vector<string> insertDecimal(string s){\n int n = s.length();\n \n vector<string> v;\n \n if(n == 0)\n return {};\n if(n == 1)\n return {s};\n \n if(s[0] == \'0\' && s[n-1] == \'0\')\n return {};\n if(s[0] == \'0\')\n return {"0."+s.substr(1)};\n if(s[n-1] == \'0\')\n return {s};\n v.emplace_back(s);\n for(int i = 1; i<n; i++){\n v.emplace_back(s.substr(0,i)+"."+s.substr(i));\n }\n return v;\n \n }\n vector<string> ambiguousCoordinates(string s) {\n int n = s.length();\n vector<string> ans;\n \n for(int i = 1; i<n-2; i++){\n string s1 = s.substr(1,i);\n string s2 = s.substr(i+1,n-i-2);\n \n //cout<<s1<<" "<<s2<<endl;\n \n vector<string> v1 = insertDecimal(s1);\n vector<string> v2 = insertDecimal(s2);\n \n for(string s1 : v1){\n for(string s2 : v2){\n ans.emplace_back("("+s1+", "+s2+")");\n }\n }\n }\n return ans;\n }\n};\n```\n**Time complexity** - O(n^3) | 2 | 1 | ['C', 'C++'] | 1 |
ambiguous-coordinates | C++ Solution with some comments | c-solution-with-some-comments-by-shtanri-2zko | \nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string S) {\n // First get rid of paranthesis at the both end\n S.erase(0, 1) | shtanriverdi | NORMAL | 2021-03-18T16:49:54.326199+00:00 | 2021-03-18T16:49:54.326242+00:00 | 244 | false | ```\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string S) {\n // First get rid of paranthesis at the both end\n S.erase(0, 1);\n S.pop_back();\n vector<string> result;\n vector<pair<string, string>> valids;\n int size = S.size();\n // Without dots\n for (int i = 0; i < size - 1; i++) {\n string A = S.substr(0, i + 1);\n string B = S.substr(i + 1, size - i + 1);\n valids.push_back({A, B});\n }\n // With Dots\n for (int i = 0; i < valids.size(); i++) {\n vector<string> left = { valids[i].first }, right = { valids[i].second };\n if (valids[i].first.size() > 1) {\n for (int j = 1; j < valids[i].first.size(); j++) {\n string withDotL = valids[i].first;\n withDotL.insert(j, 1, \'.\');\n left.push_back(withDotL);\n }\n }\n if (valids[i].second.size() > 1) {\n for (int j = 1; j < valids[i].second.size(); j++) {\n string withDotR = valids[i].second;\n withDotR.insert(j, 1, \'.\');\n right.push_back(withDotR);\n }\n }\n // Start checking validity\n for (int i = 0; i < left.size(); i++) {\n for (int j = 0; j < right.size(); j++) {\n if (isValid(left[i]) && isValid(right[j])) {\n result.push_back("(" + left[i] + ", " + right[j] + ")");\n }\n }\n }\n }\n return result;\n }\n \n // Valid 0, 0.X\n // Invalid: "5.0", "00", "0.0", "0.00", "1.0", "001", "00.01"\n bool isValid(string &s) {\n // Single char\n if (s.size() == 1) {\n return true;\n }\n // Invalid case: 0xxx0\n if (s[0] == \'0\') {\n // Only valid 0.xxx\n if (s[1] != \'.\') {\n return false;\n }\n // 00, 0xx0\n if (s.back() == \'0\' || s[1] == \'0\') {\n return false;\n }\n return true;\n }\n // Invalid case: xxx.0\n if (s.back() == \'0\') {\n // Only valid case xxx0\n if (s.find(\'.\') == std::string::npos) {\n return true;\n }\n return false;\n }\n return true;\n }\n};\n``` | 2 | 0 | ['C'] | 0 |
ambiguous-coordinates | JavaScript 100% with comments | javascript-100-with-comments-by-mamatela-2zhl | \nfunction solution(S) {\n S = S.slice(1, S.length - 1);\n let arr = [];\n\n // Separate in 2 parts. All possible ways (just put comma in all possible | mamatela | NORMAL | 2020-09-23T20:44:57.616091+00:00 | 2020-09-23T20:44:57.616121+00:00 | 139 | false | ```\nfunction solution(S) {\n S = S.slice(1, S.length - 1);\n let arr = [];\n\n // Separate in 2 parts. All possible ways (just put comma in all possible places).\n for (let i = 1; i < S.length; i++) {\n // get all possible (distinct) numbers that a string can be converted to. Do this for string1 and string2\n let p1 = combos(S.slice(0, i));\n let p2 = combos(S.slice(i));\n\n\n if (p1.length && p2.length) {\n for (let x1 of p1) {\n for (let x2 of p2) {\n arr.push([x1, x2]);\n }\n }\n }\n }\n return arr.map(e => `(${e[0]}, ${e[1]})`);\n}\n\n// get all possible (distinct) numbers that a string can be converted to.\nfunction combos(s) {\n let set = new Set(); // Use set so that it keeps distinct values\n if (String(Number(s)).length === s.length) set.add(Number(s));\n if (s.length === 1) return [...set];\n\n // Just put a dot in all possible places.\n for (let i = 1; i < s.length; i++) {\n let x = Number(s.slice(0, i) + \'.\' + s.slice(i));\n\n // Don\'t add if some digits were lost during convert (e.g. 0012 --> 12)\n if (String(x).length === (s.length + 1)) set.add(x);\n }\n return [...set];\n}\n``` | 2 | 0 | [] | 0 |
ambiguous-coordinates | Simple C++ solution | simple-c-solution-by-caspar-chen-hku-xwh1 | \nclass Solution {\npublic:\n bool check(string s, bool issecword){\n int n=s.length();\n\t\t// Logic explained above\n if(issecword){\n | caspar-chen-hku | NORMAL | 2020-05-20T09:43:24.018986+00:00 | 2020-05-20T09:43:24.019020+00:00 | 218 | false | ```\nclass Solution {\npublic:\n bool check(string s, bool issecword){\n int n=s.length();\n\t\t// Logic explained above\n if(issecword){\n if(n>0 && s[n-1]==\'0\') return false;\n }\n else{\n if(n>1 && s[0]==\'0\') return false;\n }\n return true;\n }\n\n vector<string> ambiguousCoordinates(string S) {\n vector<string> res;\n S=S.substr(1,S.length()-2);\n int n=S.length();\n\n for(int i=1;i<n;i++){\n string s1=S.substr(0,i);\n string s2=S.substr(i);\n vector<string> res1, res2;\n\t\t\t\n if(check(s1, false)) res1.push_back(s1);\n if(check(s2, false)) res2.push_back(s2);\n\t\t\t\n for(int j=1;j<s1.length();j++){\n string first=s1.substr(0,j);\n string second=s1.substr(j);\n if(check(first, false) && check(second, true)) res1.push_back(first+"."+second);\n }\n \n for(int j=1;j<s2.length();j++){\n string first=s2.substr(0,j);\n string second=s2.substr(j);\n if(check(first, false) && check(second, true)) res2.push_back(first+"."+second);\n }\n\t\t\t\n for(auto left:res1){\n for(auto right:res2){\n res.push_back("(" + left + ", "+ right + ")");\n }\n }\n }\n return res;\n }\n};\n``` | 2 | 0 | [] | 1 |
ambiguous-coordinates | Accepted C# Solution | accepted-c-solution-by-maxpushkarev-1h4f | \n public class Solution\n {\n public IList<string> AmbiguousCoordinates(string s)\n {\n s = s.Substring(1, s.Length - 2);\n | maxpushkarev | NORMAL | 2020-02-13T05:14:51.796759+00:00 | 2020-02-13T05:14:51.796809+00:00 | 147 | false | ```\n public class Solution\n {\n public IList<string> AmbiguousCoordinates(string s)\n {\n s = s.Substring(1, s.Length - 2);\n IList<string> res = new List<string>();\n for (int i = 1; i < s.Length; i++)\n {\n var left = s.Substring(0, i);\n var right = s.Substring(i, s.Length - i);\n\n\n IList<string> lefts = new List<string>();\n IList<string> rights = new List<string>();\n\n if (!(left.Length >= 2 && left[0] == \'0\'))\n {\n lefts.Add(left);\n }\n\n\n if (!(right.Length >= 2 && right[0] == \'0\'))\n {\n rights.Add(right);\n }\n\n for (int j = 1; j < left.Length; j++)\n {\n var leftLeft = left.Substring(0, j);\n if (j > 1 && leftLeft[0] == \'0\')\n {\n continue;\n }\n var leftRight = left.Substring(j, left.Length - j);\n\n if (leftRight.Length > 1 && leftRight[leftRight.Length - 1] == \'0\')\n {\n continue;\n }\n\n\n var cand = $"{leftLeft}.{leftRight}";\n if (int.Parse(leftRight) == 0)\n {\n continue;\n }\n lefts.Add(cand);\n }\n\n\n for (int j = 1; j < right.Length; j++)\n {\n var rightLeft = right.Substring(0, j);\n if (j > 1 && rightLeft[0] == \'0\')\n {\n continue;\n }\n var rightRight = right.Substring(j, right.Length - j);\n\n if (rightRight.Length > 1 && rightRight[rightRight.Length - 1] == \'0\')\n {\n continue;\n }\n\n var cand = $"{rightLeft}.{rightRight}";\n if (int.Parse(rightRight) == 0)\n {\n continue;\n }\n rights.Add(cand);\n }\n\n foreach (var l in lefts)\n {\n foreach (var r in rights)\n {\n res.Add($"({l}, {r})");\n }\n }\n\n }\n return res;\n }\n }\n``` | 2 | 0 | [] | 0 |
ambiguous-coordinates | [Java] Super Clear Solution | java-super-clear-solution-by-ophunter-b5he | \nclass Solution {\n private List<String> sub(String s) {\n if (s.length() == 1) return Collections.singletonList(s);\n\n List<String> ans = ne | ophunter | NORMAL | 2019-07-05T07:31:20.113108+00:00 | 2019-07-05T07:31:20.113140+00:00 | 228 | false | ```\nclass Solution {\n private List<String> sub(String s) {\n if (s.length() == 1) return Collections.singletonList(s);\n\n List<String> ans = new ArrayList<>();\n if (s.charAt(0) != \'0\') {\n ans.add(s);\n for (int i = 1; i < s.length() && !s.endsWith("0"); i++) {\n ans.add(s.substring(0, i) + "." + s.substring(i));\n }\n } else if (!s.endsWith("0")) {\n ans.add(s.substring(0, 1) + "." + s.substring(1));\n }\n\n return ans;\n }\n\n public List<String> ambiguousCoordinates(String S) {\n List<String> ans = new ArrayList<>();\n List<String> left;\n List<String> right;\n\n for (int i = 2; i < S.length() - 1; i++) {\n left = sub(S.substring(1, i));\n right = sub(S.substring(i, S.length() - 1));\n\n if (!left.isEmpty() && !right.isEmpty()) {\n for (String l : left) {\n for (String r : right) {\n ans.add("(" + l + ", " + r + ")");\n }\n }\n }\n }\n\n return ans;\n }\n}\n``` | 2 | 0 | [] | 0 |
ambiguous-coordinates | neat python3 solution | neat-python3-solution-by-yecye-6ny8 | \nclass Solution:\n def ambiguousCoordinates(self, S):\n """\n :type S: str\n :rtype: List[str]\n """\n \n def str2 | yecye | NORMAL | 2018-04-15T04:37:57.305945+00:00 | 2018-10-08T17:41:19.203925+00:00 | 196 | false | ```\nclass Solution:\n def ambiguousCoordinates(self, S):\n """\n :type S: str\n :rtype: List[str]\n """\n \n def str2digits(s):\n if s == \'0\':\n return [\'0\']\n if s.startswith(\'0\') and s.endswith(\'0\'):\n return []\n if s.startswith(\'0\'):\n return [\'0.\'+s[1:]]\n if s.endswith(\'0\'):\n return [s]\n ans = [s]\n for i in range(1, len(s)):\n ans.append(s[:i]+\'.\'+s[i:])\n return ans\n \n ans = []\n \n s = S[1:-1]\n for i in range(1, len(s)):\n first = str2digits(s[:i])\n second = str2digits(s[i:])\n for x in first:\n for y in second:\n ans.append(\'(\'+x+\', \'+y+\')\')\n return ans\n \n``` | 2 | 2 | [] | 0 |
ambiguous-coordinates | Easy C++ Solution | easy-c-solution-by-farhanc-1nap | \n\n# Code\n\nclass Solution {\npublic:\n vector<string>res;\n vector<string>putdot(string s){\n vector<string>temp;\n temp.push_back(s);\n | farhanc | NORMAL | 2024-01-07T11:43:37.258111+00:00 | 2024-01-07T11:43:37.258135+00:00 | 181 | false | \n\n# Code\n```\nclass Solution {\npublic:\n vector<string>res;\n vector<string>putdot(string s){\n vector<string>temp;\n temp.push_back(s);\n for(int i=1;i<s.length();i++){\n temp.push_back(s.substr(0,i)+"."+s.substr(i));\n }\n return temp;\n }\n bool isValid(string s) {\n if (s.find(\'.\') != string::npos) {\n size_t dotPosition = s.find(\'.\');\n string integerPart = s.substr(0, dotPosition);\n string decimalPart = s.substr(dotPosition + 1);\n\n if (integerPart != "0" && integerPart[0] == \'0\') {\n return false;\n } else {\n return !decimalPart.ends_with("0");\n }\n } else {\n if (s == "0") {\n return true;\n } else {\n return !s.starts_with("0");\n }\n }\n}\n void helper(string s1,string s2){\n vector<string>v1=putdot(s1);\n vector<string>v2=putdot(s2);\n for(string &a:v1){\n if(isValid(a)){\n for(string &b:v2){\n if(isValid(b)){\n res.push_back("("+a+", "+b+")");\n }\n }\n }\n }\n }\n\n vector<string> ambiguousCoordinates(string s) {\n string s2=s.substr(1,s.length()-2);\n for(int i=1;i<s2.length();i++){\n helper(s2.substr(0,i),s2.substr(i));\n }\n return res;\n }\n};\n\n``` | 1 | 0 | ['C++'] | 0 |
ambiguous-coordinates | Solution | solution-by-deleted_user-1nme | C++ []\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string s) {\n string cur1 = "";\n string cur2 = "";\n vector<str | deleted_user | NORMAL | 2023-05-02T13:24:51.293180+00:00 | 2023-05-02T14:10:20.097991+00:00 | 524 | false | ```C++ []\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string s) {\n string cur1 = "";\n string cur2 = "";\n vector<string> res;\n bool confirmedFirstPart = false;\n bool usedDot = false;\n backtrack(s, cur1, cur2, res, 0, confirmedFirstPart, usedDot);\n return res;\n }\n void backtrack(string& s, string& cur1, string& cur2, vector<string>& res, int index, bool& confirmedFirstPart, bool& usedDot)\n {\n if (index == s.length())\n {\n if (confirmedFirstPart == true)\n {\n if (cur2.size() != 2 && (cur2[cur2.size() - 2] == \'0\') && (cur2[0] == \'0\')) return;\n res.push_back(cur1 + cur2);\n }\n return;\n }\n if (s[index] != \'(\' && s[index] != \')\')\n {\n if (usedDot == false && index != s.length() - 2)\n {\n if (!confirmedFirstPart)\n {\n cur1.push_back(s[index]);\n cur1.push_back(\'.\');\n usedDot = true;\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur1.pop_back();\n cur1.pop_back();\n usedDot = false;\n }\n else\n {\n cur2.push_back(s[index]);\n cur2.push_back(\'.\');\n usedDot = true;\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur2.pop_back();\n cur2.pop_back();\n usedDot = false;\n }\n }\n if (confirmedFirstPart == false && index != s.length() - 2)\n {\n if (!(usedDot == true && s[index] == \'0\'))\n {\n cur1.push_back(s[index]);\n cur1.push_back(\',\');\n cur1.push_back(\' \');\n confirmedFirstPart = true;\n bool usedDotCopy = usedDot;\n usedDot = false;\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur1.pop_back();\n cur1.pop_back();\n cur1.pop_back();\n confirmedFirstPart = false;\n usedDot = usedDotCopy;\n }\n }\n if (!confirmedFirstPart) \n {\n if (!(cur1.size() == 1 && s[index] == \'0\'))\n {\n cur1.push_back(s[index]);\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur1.pop_back();\n }\n }\n else\n {\n if (!(cur2.empty() && index != s.length() - 2 && s[index] == \'0\') && \n !(usedDot && index == s.length() - 2 && s[index] == \'0\'))\n {\n cur2.push_back(s[index]);\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur2.pop_back();\n }\n }\n }\n else\n {\n if (s[index] == \'(\')\n {\n cur1.push_back(\'(\');\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur1.pop_back();\n }\n else\n {\n cur2.push_back(\')\');\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur2.pop_back();\n }\n }\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def gen_nums(self, s):\n ans = []\n if s == "0" or s[0] != "0":\n ans.append(s)\n \n if s[-1] == \'0\':\n return ans\n \n if s[0] == \'0\':\n return ans + [\'0.\' + s[1:]]\n\n for i in range(1, len(s)):\n ans.append(s[:i] + \'.\' + s[i:])\n return ans\n\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s[1:-1]\n res = []\n for left_len in range(1, len(s)):\n l = self.gen_nums(s[:left_len])\n r = self.gen_nums(s[left_len:])\n for n1 in l:\n for n2 in r:\n res.append(f\'({n1}, {n2})\')\n \n return res\n```\n\n```Java []\nclass Solution {\n public List<String> helper (String s) {\n List<String> answer = new ArrayList<> ();\n if (s.length () == 1) {\n answer.add (s);\n return answer;\n }\n else if (s.charAt (0) == \'0\' && s.charAt (s.length () - 1) == \'0\') {\n return answer;\n }\n else if (s.charAt (0) == \'0\') {\n StringBuilder sb = new StringBuilder ();\n sb.append (s.charAt (0)).append (".").append (s.substring (1));\n answer.add (sb.toString ());\n return answer;\n }\n else if (s.charAt (s.length () - 1) == \'0\') {\n answer.add (s);\n return answer;\n }\n answer.add (s);\n for (int i = 1; i < s.length (); i++) {\n StringBuilder sb = new StringBuilder ();\n sb.append (s.substring (0, i)).append (".").append (s.substring (i));\n answer.add (sb.toString ());\n }\n return answer;\n }\n public List<String> ambiguousCoordinates(String s) { \n List<String> answer = new ArrayList<> ();\n for (int i = 2; i < s.length () - 1; i++) {\n List<String> leftLists = helper (s.substring (1, i));\n List<String> rightLists = helper (s.substring (i, s.length () - 1));\n \n for (String leftString : leftLists) {\n for (String rightString : rightLists) {\n StringBuilder sb = new StringBuilder ();\n sb.append ("(").append (leftString).append (", ").append (rightString).append (")");\n answer.add (sb.toString ());\n }\n }\n }\n return answer;\n }\n}\n```\n | 1 | 0 | ['C++', 'Java', 'Python3'] | 1 |
ambiguous-coordinates | c# : Easy Solution | c-easy-solution-by-rahul89798-jp8u | \tpublic class Solution\n\t{\n\t\tList ans;\n\t\tpublic IList AmbiguousCoordinates(string s)\n\t\t{\n\t\t\tans = new List();\n\t\t\tSolve(s, new List(), 1);\n\n | rahul89798 | NORMAL | 2021-12-20T05:49:01.702766+00:00 | 2021-12-20T05:49:01.702808+00:00 | 108 | false | \tpublic class Solution\n\t{\n\t\tList<string> ans;\n\t\tpublic IList<string> AmbiguousCoordinates(string s)\n\t\t{\n\t\t\tans = new List<string>();\n\t\t\tSolve(s, new List<string>(), 1);\n\n\t\t\treturn ans;\n\t\t}\n\n\t\tprivate void Solve(string s, List<string> str, int idx)\n\t\t{\n\t\t\tif(str.Count >= 2)\n\t\t\t{\n\t\t\t\tif (IsValid(str, s.Length - 2))\n\t\t\t\t\tans.Add(\'(\' + str[0] + ", " + str[1] + \')\');\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor(int i = idx; i < s.Length - 1; i++)\n\t\t\t{\n\t\t\t\tstr.Add(s.Substring(idx, i - idx + 1));\n\t\t\t\tSolve(s, str, i + 1);\n\t\t\t\tstr.RemoveAt(str.Count - 1);\n\t\t\t}\n\n\t\t\tfor(int i = idx; i < s.Length - 1; i++)\n\t\t\t{\n\t\t\t\tstring temp = s.Substring(idx, i - idx + 1) + \'.\';\n\t\t\t\tfor(int j = i + 1; j < s.Length - 1; j++)\n\t\t\t\t{\n\t\t\t\t\tstr.Add(temp + s.Substring(i + 1, j - i));\n\t\t\t\t\tSolve(s, str, j + 1);\n\t\t\t\t\tstr.RemoveAt(str.Count - 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprivate bool IsValid(List<string> str, int stringLength)\n\t\t{\n\t\t\treturn !string.IsNullOrWhiteSpace(str[0]) &&\n\t\t\t\t!string.IsNullOrWhiteSpace(str[1]) &&\n\t\t\t\t(str[0][0] != \'0\' || str[0].Length == 1 || str[0][1] == \'.\') &&\n\t\t\t\t(str[1][0] != \'0\' || str[1].Length == 1 || str[1][1] == \'.\') &&\n\t\t\t\t(!str[0].Contains(\'.\') || str[0][^1] != \'0\') &&\n\t\t\t\t(!str[1].Contains(\'.\') || str[1][^1] != \'0\') &&\n\t\t\t\t(str[0].Replace(".", string.Empty).Length + str[1].Replace(".", string.Empty).Length >= stringLength);\n\t\t}\n\t} | 1 | 0 | ['Backtracking'] | 0 |
ambiguous-coordinates | C++ Solution | c-solution-by-simplestman-yzo4 | \nclass Solution {\npublic:\n int len;\n vector<string>ans;\n string helper(string s,int k){\n if(s.size() == 1) return s;\n if(k>=2){\n | SimplestMan | NORMAL | 2021-08-26T13:55:53.965355+00:00 | 2021-08-26T13:55:53.965386+00:00 | 115 | false | ```\nclass Solution {\npublic:\n int len;\n vector<string>ans;\n string helper(string s,int k){\n if(s.size() == 1) return s;\n if(k>=2){\n if(s[0] == \'0\') return "-1";\n }\n if(s[s.size()-1] == \'0\'){\n if(k != s.size()) return "-1";\n }\n if(k == s.size()) return s;\n string res = s.substr(0,k)+"."+s.substr(k);\n return res;\n }\n void backtrack(string s,int pos,string prev){\n if(prev.size()>0){\n for(int i = 1;i<=len-pos;i++){\n string t = helper(s.substr(pos),i);\n if(t == "-1") continue;\n else ans.push_back("("+prev+", "+t+")");\n }\n return;\n }\n else{\n for(int i = 1;i<len;i++){\n string temp = s.substr(0,i);\n for(int j = 1;j<=i;j++){\n string t = helper(temp,j);\n if(t == "-1") continue;\n backtrack(s,i,t);\n }\n }\n }\n }\n vector<string> ambiguousCoordinates(string s) {\n s = s.substr(1,s.size()-2);\n len = s.size();\n backtrack(s,0,"");\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
ambiguous-coordinates | C++ Solution with explanation | c-solution-with-explanation-by-rmallela0-cxa1 | \n /*\n * input: "(123)"\n * First we will assign commas\n * 123\n * |\n * ----------\n * | rmallela0426 | NORMAL | 2021-06-04T05:38:10.881680+00:00 | 2021-06-04T05:45:58.683756+00:00 | 268 | false | ```\n /*\n * input: "(123)"\n * First we will assign commas\n * 123\n * |\n * ----------\n * | |\n * 1, 23 12, 3\n *\n * Now we have 2 pairs after putting comma. Now try tp put the \n * decimal point\n *\n * 1, 2.3 1.2, 3\n * So there are total 4 combinations (1, 23), (1, 2.3), (12, 3), (1.2, 3)\n * While applying decimal point, we need to exclude the nos that are "00"\n * "0.0", "0.00", "1.0", "001", "00.01", ".1"\n */\n\n //Function that will generate all nos (including decimal)\n void generateNumbers(string s, vector<string>& out) {\n // If the string has only one character then there won\'t be any\n // decimal point, so pushing the num and returning\n if (s.length() == 1) {\n out.push_back(s);\n return;\n }\n \n // Check if the first char is zero or not\n if (s[0] != \'0\') {\n // The first char is not zero, so we have a valid number and one\n // combination, push it to res\n // Eg: s = 12 for input 123, then 12 is one combination of input.\n out.push_back(s);\n }\n else {\n // First char is zero, check if the last char is zero, if so the\n // number had extraneous zeros which is not valid. If last char is\n // not zero then we add a decimal point after the first char and\n // return from the function\n // Eg: s = "01230" return empty vecctor\n // s = "01234" return 0.1234\n if (s.back() != \'0\') {\n out.push_back("0." + s.substr(1));\n }\n \n return;\n }\n\n // Check if the last char is 0, if so return\n // Eg: s = "10" skip as 1.0 not allowed\n if (s.back() == \'0\') {\n return;\n }\n \n // Now that we have valid numbers, loop all characters and find the\n // decimal combinations.\n for (int i = 1; i < s.length(); i++) {\n out.push_back(s.substr(0, i) + "." + s.substr(i));\n }\n \n return;\n }\n \n vector<string> ambiguousCoordinates(string s) {\n // Generate a string by excluding open and close\n // brackets\n string s2 = s.substr(1, s.length() - 2);\n \n // Variable to store the length of input\n int n = s2.length();\n \n // Vector to store result\n vector<string> res;\n // Left and right vectors are for storing the number combinations for\n // left and right values\n vector<string> left;\n vector<string> right;\n \n // Traverse each char in string starting from 1 as we need\n // at least one char\n for (int i = 1; i < n; i++) {\n // Generate the left half and right half ie.., if input is 123\n // below logic will generate it as 1 and 23\n // Send it to generate numbers function to get the decimal nos\n // out of it\n generateNumbers(s2.substr(0, i), left); \n generateNumbers(s2.substr(i), right);\n \n // Now that we have all combinations for this number, put it in\n // result by adding space between nos and open and close brackets\n for (string& lnum : left) {\n for (string& rnum : right) {\n res.push_back("(" + lnum + ", " + rnum + ")");\n }\n }\n // Clear the vectors for the next set of generated nums\n left.clear();\n right.clear();\n }\n \n // return the result\n return res;\n }\n``` | 1 | 0 | [] | 0 |
ambiguous-coordinates | Bhayank code h bhai! C++ | bhayank-code-h-bhai-c-by-aaditya-pal-t00t | c++\nclass Solution {\npublic:\n bool valpre(string &s){\n if(s.size()==1) return true;\n if(s[0]==\'0\') return false;\n return true;\n | aaditya-pal | NORMAL | 2021-06-03T16:41:34.458230+00:00 | 2021-06-03T16:41:34.458267+00:00 | 158 | false | ```c++\nclass Solution {\npublic:\n bool valpre(string &s){\n if(s.size()==1) return true;\n if(s[0]==\'0\') return false;\n return true;\n }\n bool valsuff(string &s){\n if(s[s.size()-1]==\'0\') return false;\n return true;\n }\n bool isvalid(string &s){\n if(s.size()==1) return true;\n int i = 0;\n string pre = "";\n string suff = "";\n while(i<s.size()&&s[i]!=\'.\'){\n pre+=s[i];\n i++;\n }\n if(i==s.size()){\n if(s[0]==\'0\') return false;\n return true;\n }\n suff = s.substr(i,s.size());\n return valpre(pre)&&valsuff(suff);\n \n }\n vector<string>make_coordinate(string &s){\n vector<string>res;\n res.push_back(s);\n if(s.size()==1) return res;\n string prefix = "";\n string suffix = "";\n for(int i = 0;i<s.size()-1;i++){\n prefix+=s[i];\n suffix = s.substr(i+1,s.size());\n if(suffix.size()==0){\n res.push_back(prefix);\n continue;\n }\n string curr = "";\n curr+=prefix;\n curr+=\'.\';\n curr+=suffix;\n res.push_back(curr);\n }\n return res;\n }\n vector<string> ambiguousCoordinates(string s) {\n s.erase(s.begin());\n s.erase(--s.end());\n string prefix = "";\n string suffix;\n vector<string>ans;\n string temp = "01";\n for(int i = 0;i<s.size()-1;i++){\n prefix+=s[i];\n suffix = s.substr(i+1,s.size());\n vector<string>leftcord = make_coordinate(prefix);\n vector<string>rightcord = make_coordinate(suffix);\n for(auto &s1 : leftcord){\n for(auto &s2 : rightcord){\n if(isvalid(s1)==false||isvalid(s2)==false) continue;\n string curr = "(";\n curr+=s1;\n curr+=", ";\n curr+=s2;\n curr+=\')\';\n ans.push_back(curr);\n }\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
ambiguous-coordinates | c++ cartesian product (faster than 100%) | c-cartesian-product-faster-than-100-by-_-kn99 | \nclass Solution {\nprivate:\n bool Prefix(string s)\n {\n int n=(int)s.length();\n if(n==1) return true;\n if(s[0]==\'0\') return fa | _Akansh | NORMAL | 2021-05-14T21:25:32.446506+00:00 | 2021-05-14T21:25:48.534494+00:00 | 306 | false | ```\nclass Solution {\nprivate:\n bool Prefix(string s)\n {\n int n=(int)s.length();\n if(n==1) return true;\n if(s[0]==\'0\') return false;\n return true;\n }\n bool Suffix(string s)\n {\n int n=(int)s.length();\n if(s[n-1]==\'0\') return false;\n return true;\n }\n vector<string> generate(string s)\n {\n vector<string> g;\n int n=(int)s.length();\n if(Prefix(s)) g.push_back(s);\n for(int i=1;i<n;i++)\n {\n string left=s.substr(0,i);\n string right=s.substr(i);\n if(Prefix(left)==true and Suffix(right)==true){\n g.push_back(left+"."+right);\n }\n }\n return g;\n }\npublic:\n vector<string> ambiguousCoordinates(string str) {\n vector<string> sol;\n string s=str.substr(1,str.length()-2);\n int n=(int)s.length();\n \n for(int i=1;i<n;i++)\n {\n vector<string> left=generate(s.substr(0,i));\n vector<string> right=generate(s.substr(i));\n for(auto l:left)\n {\n for(auto r:right) sol.push_back("("+l+", "+r+")");\n }\n }\n return sol;\n }\n};\n\n``` | 1 | 0 | ['C'] | 0 |
ambiguous-coordinates | swift solution with explanation | swift-solution-with-explanation-by-codea-pz18 | \nclass Solution {\n func ambiguousCoordinates(_ s: String) -> [String] {\n var str = Array(s)\n str.removeFirst()\n str.removeLast()\n | codeawhile | NORMAL | 2021-05-14T09:30:24.532833+00:00 | 2021-05-14T09:30:24.532864+00:00 | 156 | false | ```\nclass Solution {\n func ambiguousCoordinates(_ s: String) -> [String] {\n var str = Array(s)\n str.removeFirst()\n str.removeLast()\n var ans: [String] = []\n var lefts: [String] = []\n var rights: [String] = []\n for i in 0..<str.count-1 {\n lefts = makeStrings(str, 0, i)\n rights = makeStrings(str, i+1, str.count-1)\n for left in lefts {\n for right in rights {\n let temp = "(" + left + ", " + right + ")"\n ans.append(temp)\n }\n }\n }\n return ans\n }\n\n func makeStrings(_ s: [Character], _ i: Int, _ j: Int) -> [String] {\n var str = s[i...j]\n var result: [String] = []\n for idx in i...j { // Array.Slice is only a view of an original arran, so we use original index rather than 0..<str.count, which will cause index out of bounds error\n var left: [Character] = []\n var right: [Character] = []\n \n if idx == j { // reach the last index, do not need to split\n left.append(contentsOf: Array(str[i...j]))\n right = []\n } else {\n left = Array(str[i...idx])\n right = Array(str[idx+1...j])\n }\n if !(left.count > 1 && left.first! == "0") { // case like left = "01" right = "23" we do not add dot\n if right.isEmpty {\n result.append(String(left))\n } else {\n var temp = left\n temp.append(".")\n temp.append(contentsOf: right)\n if temp.last! != "0" { // case like "1.0" is not eligible\n result.append(String(temp))\n }\n \n }\n }\n }\n return result\n }\n}\n\n``` | 1 | 0 | ['Swift'] | 0 |
ambiguous-coordinates | [C++, Explanation, Easy to Understand with Comments] | c-explanation-easy-to-understand-with-co-y29u | First, we process the input string to remove the ( and ) characters at the beginning and end respectively. Now, we can place commas at n-1 positions, where n is | programmer1234 | NORMAL | 2021-05-14T04:50:51.463752+00:00 | 2021-05-14T04:53:24.796346+00:00 | 49 | false | First, we process the input string to remove the `(` and `)` characters at the beginning and end respectively. Now, we can place commas at `n-1` positions, where `n` is the length of the processed string. For each of these cases, we divide the string into left and right subparts. For each subpart, we place a decimal point after each character, except in the following edge cases:\n1. If the last character of the subpart is `0`, we return, since there is no point in putting a decimal point with a zero at the end.\n2. If the subpart has a leading `0`, then we can place a decimal point only after the first character i.e. only after the first `0`\n\nHere is the code:\n```\nclass Solution {\npublic:\n vector <string> putDecimal(string &s, int startIdx, int endIdx){\n //if subpart\'s len == endIdx-startIdx+1 == 1, return itself\n if(endIdx - startIdx + 1 == 1)\n return {s.substr(startIdx, 1)};\n vector <string> ret;\n // if subpart does not contain a leading zero, we can add the whole subpart to the result without placing a decimal point \n if(s[startIdx] != \'0\')\n ret.push_back(s.substr(startIdx, endIdx - startIdx + 1));\n //edge case 1 mentioned above\n if(s[endIdx] == \'0\')\n return ret;\n for(int i = startIdx ; i < endIdx ; i++){\n //edge case 2 mentioned above\n if(s[startIdx] == \'0\' && i > startIdx)\n break;\n string tmp = s.substr(startIdx, i - startIdx + 1) + \'.\' + s.substr(i + 1, endIdx - i);\n ret.push_back(tmp);\n }\n return ret;\n }\n vector<string> ambiguousCoordinates(string s) {\n int n = s.size();\n //preprocess the input string\n s = s.substr(1, n-2);\n vector <string> ans;\n n = s.size();\n // trying to put commas at all the valid positions\n for(int i = 0 ; i < n-1 ; i++){\n // divide into left and right subparts\n vector <string> part1 = putDecimal(s, 0, i), part2 = putDecimal(s, i+1, n-1);\n //combine the results of the left and right subparts\n for(string s1:part1){\n for(string s2:part2)\n ans.push_back(\'(\' + s1 + ", " + s2 + \')\');\n }\n }\n return ans;\n }\n};\n``` | 1 | 1 | ['C++'] | 0 |
ambiguous-coordinates | [Java] 100% 2ms Fast, Simple, Explanation | java-100-2ms-fast-simple-explanation-by-y8bqj | This code runs in 2ms or sometimes 3ms.\n\nThe execution speed comes from converting the original String to a char[] array, then do all the testing and building | dudeandcat | NORMAL | 2021-05-14T01:19:38.430240+00:00 | 2021-05-15T06:54:00.471720+00:00 | 214 | false | This code runs in 2ms or sometimes 3ms.\n\nThe execution speed comes from converting the original `String` to a `char[]` array, then do all the testing and building of any valid coordinate strings directly from the `char[]` array, without any slow substring creation. The code works with comma and any decimal point positions that are indexes into the `char[]` array, without actually putting any comma character or decimal point character into the `char[]` array. The index for the comma or any decimal point are the index of the character in the `char[]` array that they would appear before, but they are **never** inserted into the `char[]`. The loops that provide the comma or decimal point indexes, *always* give valid positions.\n\nThe basic code structure it to try all possible comma positions. For a comma position, check if the first number is a valid integer, and try all possible decimal point positions for the first number and check if the first number is a valid decimal point\'ed number for that decimal point position. For all valid first numbers, check if the second number would be a valid integer, or try all decimal point positions in the second number. If two valid numbers are found, then call a method to build the valid coordinate string and add it to the result list.\n\nIf useful, please up-vote.\n```\nclass Solution {\n public List<String> ambiguousCoordinates(String s) {\n char[] sc = s.toCharArray();\n List<String> result = new ArrayList();\n StringBuilder sb = new StringBuilder();\n \n // Loop through all possible index positions for the comma.\n for (int commaPos = 2; commaPos < sc.length - 1; commaPos++) {\n \n // If first number if a valid integer without any decimal point.\n if (isValidNum(sc, 1, commaPos - 1)) {\n if (isValidNum(sc, commaPos, sc.length - 2))\n buildNums(result, sb, sc, 1, commaPos-1, 0, commaPos, sc.length-2, 0);\n for (int dp2Idx = commaPos + 1; dp2Idx < sc.length - 1; dp2Idx++)\n if (isValidDPNum(sc, commaPos, sc.length - 2, dp2Idx))\n buildNums(result, sb, sc, 1, commaPos-1, 0, commaPos, sc.length-2, dp2Idx);\n }\n \n // Check all possible decimal point positions for the first number.\n for (int dp1Idx = 2; dp1Idx < commaPos; dp1Idx++) {\n if (isValidDPNum(sc, 1, commaPos - 1, dp1Idx)) {\n if (isValidNum(sc, commaPos, sc.length - 2))\n buildNums(result, sb, sc, 1, commaPos-1, dp1Idx, commaPos, sc.length-2, 0);\n for (int dp2Idx = commaPos + 1; dp2Idx < sc.length - 1; dp2Idx++)\n if (isValidDPNum(sc, commaPos, sc.length - 2, dp2Idx))\n buildNums(result, sb, sc, 1, commaPos-1, dp1Idx, commaPos, sc.length-2, dp2Idx);\n }\n }\n }\n return result;\n }\n \n \n // Check if a number in the char[] array is a valid integer without any decimal point.\n private boolean isValidNum(char[] sc, int startIdx, int lastIdx) {\n if (sc[startIdx] == \'0\' && lastIdx - startIdx != 0) return false;\n return true;\n }\n \n \n // Check if a number in the char[] array is valid number with virtual decimal point at the specified index.\n private boolean isValidDPNum(char[] sc, int startIdx, int lastIdx, int dpIdx) {\n if ((sc[startIdx] == \'0\' && dpIdx - startIdx != 1) || sc[lastIdx] == \'0\') return false;\n return true;\n }\n \n \n // Build the result two number coordinate string and add to the List of results.\n private void buildNums(List<String> result, StringBuilder sb, char[] sc, \n int start1Idx, int last1Idx, int dp1Idx, \n int start2Idx, int last2Idx, int dp2Idx) {\n sb.setLength(0);\n sb.append(\'(\');\n if (dp1Idx == 0)\n sb.append(sc, start1Idx, last1Idx - start1Idx + 1);\n else\n sb.append(sc, start1Idx, dp1Idx - start1Idx).append(\'.\').append(sc, dp1Idx, last1Idx - dp1Idx + 1);\n sb.append(\',\').append(\' \');\n if (dp2Idx == 0)\n sb.append(sc, start2Idx, last2Idx - start2Idx + 1);\n else\n sb.append(sc, start2Idx, dp2Idx - start2Idx).append(\'.\').append(sc, dp2Idx, last2Idx - dp2Idx + 1);\n sb.append(\')\');\n result.add(sb.toString());\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
ambiguous-coordinates | Easy clean Go solution. Beats 100% | easy-clean-go-solution-beats-100-by-evle-q62b | \nfunc ambiguousCoordinates(s string) []string {\n\tvar result []string\n\n\tfor i := 2; i <= len(s)-2; i++ {\n\t\tleft, right := s[1:i], s[i:len(s)-1]\n\n\t\ti | evleria | NORMAL | 2021-05-13T20:21:31.582578+00:00 | 2021-05-13T20:21:31.582626+00:00 | 137 | false | ```\nfunc ambiguousCoordinates(s string) []string {\n\tvar result []string\n\n\tfor i := 2; i <= len(s)-2; i++ {\n\t\tleft, right := s[1:i], s[i:len(s)-1]\n\n\t\tif isLegalPart(left) && isLegalPart(right) {\n\t\t\tleftPartitions, rightPartitions := getAllPartitions(left), getAllPartitions(right)\n\n\t\t\tfor _, leftPartition := range leftPartitions {\n\t\t\t\tfor _, rightPartition := range rightPartitions {\n\t\t\t\t\tresult = append(result, fmt.Sprintf("(%s, %s)", leftPartition, rightPartition))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc isLegalPart(s string) bool {\n\treturn len(s) == 1 || s[0] != \'0\' || s[len(s)-1] != \'0\'\n}\n\nfunc getAllPartitions(s string) []string {\n\tswitch {\n\tcase len(s) == 1 || s[len(s)-1] == \'0\':\n\t\treturn []string{s}\n\tcase s[0] == \'0\':\n\t\treturn []string{fmt.Sprintf("0.%s", s[1:])}\n\tdefault:\n\t\tresult := make([]string, 1, len(s))\n\t\tresult[0] = s\n\t\tfor i := 1; i < len(s); i++ {\n\t\t\tresult = append(result, fmt.Sprintf("%s.%s", s[:i], s[i:]))\n\t\t}\n\t\treturn result\n\t}\n}\n``` | 1 | 0 | ['Go'] | 0 |
ambiguous-coordinates | 70 % :: Python | 70-python-by-tuhinnn_py-06ey | \nclass Solution:\n def putDecimal(self, num):\n ans = []\n if not int(num):\n if len(num) == 1:\n return [\'0\']\n | tuhinnn_py | NORMAL | 2021-05-13T18:01:24.500921+00:00 | 2021-05-13T18:01:24.500976+00:00 | 52 | false | ```\nclass Solution:\n def putDecimal(self, num):\n ans = []\n if not int(num):\n if len(num) == 1:\n return [\'0\']\n else:\n return []\n \n if num.startswith(\'0\'):\n return [\'0.\' + num[1:]] if not num.endswith(\'0\') else []\n \n if num.endswith(\'0\'):\n return [num]\n \n for i in range(len(num) - 1):\n # [0, i + 1), [i + 1, ..)\n left, right = num[:i + 1], num[i + 1: ]\n if not int(right):\n break\n if not right.endswith(\'0\'):\n ans.append(left + \'.\' + right)\n \n return ans + [num] if not num.startswith(\'0\') else ans\n \n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s[1: -1]\n ans = set()\n for i in range(len(s) - 1):\n left, right = s[:i + 1], s[i + 1: ]\n leftDecimals = self.putDecimal(left)\n rightDecimals = self.putDecimal(right)\n \n if leftDecimals and rightDecimals:\n for leftDecimal in leftDecimals:\n for rightDecimal in rightDecimals:\n ans.add("(" + leftDecimal + ", " + rightDecimal + ")")\n return ans\n # \n``` | 1 | 0 | [] | 0 |
ambiguous-coordinates | Rust solution | rust-solution-by-sugyan-c98h | rust\nimpl Solution {\n pub fn ambiguous_coordinates(s: String) -> Vec<String> {\n let s = s.chars().skip(1).take(s.len() - 2).collect::<Vec<_>>();\n | sugyan | NORMAL | 2021-05-13T15:35:07.732363+00:00 | 2021-05-13T15:35:07.732410+00:00 | 60 | false | ```rust\nimpl Solution {\n pub fn ambiguous_coordinates(s: String) -> Vec<String> {\n let s = s.chars().skip(1).take(s.len() - 2).collect::<Vec<_>>();\n let candidates = |v: &[char]| -> Vec<String> {\n (0..v.len())\n .filter_map(|i| {\n let s: String = if i == 0 {\n v.iter().collect()\n } else {\n v[..i]\n .iter()\n .chain(std::iter::once(&\'.\'))\n .chain(v[i..].iter())\n .collect()\n };\n if (s != "0" && s.starts_with(\'0\') && !s.starts_with("0."))\n || (s.contains(\'.\') && s.ends_with(\'0\'))\n {\n None\n } else {\n Some(s)\n }\n })\n .collect()\n };\n let mut answer = Vec::new();\n for i in 1..s.len() {\n for x in &candidates(&s[..i]) {\n for y in &candidates(&s[i..]) {\n answer.push(format!("({}, {})", x, y));\n }\n }\n }\n answer\n }\n}\n``` | 1 | 1 | ['Rust'] | 0 |
ambiguous-coordinates | [Java] Clean and Fast | Beats 100% | java-clean-and-fast-beats-100-by-lucoram-gw2r | The solution is self explanatory.\n\n\nclass Solution {\n\n public List<String> ambiguousCoordinates(String digits) {\n List<String> answer = new Arra | lucoram | NORMAL | 2021-05-13T14:35:00.360292+00:00 | 2021-05-13T14:35:00.360336+00:00 | 90 | false | The solution is self explanatory.\n\n```\nclass Solution {\n\n public List<String> ambiguousCoordinates(String digits) {\n List<String> answer = new ArrayList<>();\n char[] digitsArr = digits.toCharArray();\n int n = digitsArr.length;\n\n for (int comaIdx = 2; comaIdx < n - 1; comaIdx++) {\n String left = new String(Arrays.copyOfRange(digitsArr, 1, comaIdx));\n String right = new String(Arrays.copyOfRange(digitsArr, comaIdx, n - 1));\n\n List<String> leftWithPoint = addPoints(left);\n List<String> rightWithPoint = addPoints(right);\n\n for (String leftFloat : leftWithPoint) {\n for (String rightFloat : rightWithPoint) {\n answer.add(build(leftFloat, rightFloat, true));\n }\n }\n }\n\n return answer;\n }\n\n private List<String> addPoints(String digits) {\n\n List<String> answer = new ArrayList<>();\n\n if (isValid(digits)) {\n answer.add(digits);\n }\n\n char[] digitsArr = digits.toCharArray();\n int n = digitsArr.length;\n\n for (int pointIdx = 1; pointIdx < n; pointIdx++) {\n String left = new String(Arrays.copyOfRange(digitsArr, 0, pointIdx));\n String right = new String(Arrays.copyOfRange(digitsArr, pointIdx, n));\n String floatNum = build(left, right, false);\n\n if (isValid(floatNum)) {\n answer.add(floatNum);\n }\n }\n\n return answer;\n }\n\n private String build(String left, String right, boolean comaSep) {\n StringBuilder builder = new StringBuilder();\n\n if (comaSep) {\n builder.append("(");\n }\n\n builder.append(left);\n\n if (comaSep) {\n builder.append(", ");\n } else {\n builder.append(".");\n }\n\n builder.append(right);\n\n if (comaSep) {\n builder.append(")");\n }\n\n return builder.toString();\n }\n\n private boolean isValid(String value) {\n if (value.length() > 1 && value.charAt(1) != \'.\' && value.startsWith("0")) {\n return false;\n }\n\n if (value.contains(".") && value.endsWith("0")) {\n return false;\n }\n\n return true;\n }\n}\n``` | 1 | 0 | [] | 0 |
ambiguous-coordinates | 816 - The long answer | 816-the-long-answer-by-pgmreddy-zghy | Not a simple one :)\n\nLong answer ahead :), with a lot of code duplication. Hopefully others can understand.\n\n var ambiguousCoordinates = function (s) {\n | pgmreddy | NORMAL | 2021-05-13T12:19:43.166520+00:00 | 2021-05-13T12:39:47.635471+00:00 | 119 | false | Not a simple one :)\n\nLong answer ahead :), with a lot of code duplication. Hopefully others can understand.\n\n var ambiguousCoordinates = function (s) {\n let n = s.length;\n\n // answer array\n let A = [];\n\n // remove ( and ), reduce length by 2\n s = s.slice(1, n - 1);\n n -= 2;\n\n for (let i = 1; i < n; i++) {\n let left = s.slice(0, i);\n let right = s.slice(i);\n\n // ---------- no decimals\n\n if (\n (left.length >= 2 && left.startsWith("0")) ||\n (right.length >= 2 && right.startsWith("0"))\n ) {\n } else {\n A.push("(" + left + ", " + right + ")");\n }\n\n // ---------- left decimal\n\n for (let j = 1; j < left.length; j++) {\n left1 = left.slice(0, j);\n left2 = left.slice(j);\n if (\n (left1.length >= 2 && left1.startsWith("0")) || //\n (left2.length >= 2 && left2.endsWith("0")) || //\n +left2 === 0 || //\n (right.length >= 2 && right.startsWith("0"))\n ) {\n } else {\n A.push("(" + left1 + "." + left2 + ", " + right + ")");\n }\n }\n\n // ---------- right decimal\n\n for (let j = 1; j < right.length; j++) {\n right1 = right.slice(0, j);\n right2 = right.slice(j);\n if (\n (right1.length >= 2 && right1.startsWith("0")) || //\n (right2.length >= 2 && right2.endsWith("0")) || //\n +right2 === 0 || //\n (left.length >= 2 && left.startsWith("0"))\n ) {\n } else {\n A.push("(" + left + ", " + right1 + "." + right2 + ")");\n }\n }\n\n // ---------- left & right decimal\n\n for (let j = 1; j < left.length; j++) {\n left1 = left.slice(0, j);\n left2 = left.slice(j);\n if (\n (left1.length >= 2 && left1.startsWith("0")) || //\n (left2.length >= 2 && left2.endsWith("0")) || //\n +left2 === 0\n ) {\n } else {\n for (let j = 1; j < right.length; j++) {\n right1 = right.slice(0, j);\n right2 = right.slice(j);\n\n if (\n (right1.length >= 2 && right1.startsWith("0")) || //\n (right2.length >= 2 && right2.endsWith("0")) || //\n +right2 === 0\n ) {\n } else {\n A.push("(" + left1 + "." + left2 + ", " + right1 + "." + right2 + ")");\n }\n }\n }\n }\n\n // ---------- right & left decimal\n\n for (let j = 1; j < right.length; j++) {\n right1 = right.slice(0, j);\n right2 = right.slice(j);\n if (\n (right1.length >= 2 && right1.startsWith("0")) || //\n (right2.length >= 2 && right2.endsWith("0")) || //\n +right2 === 0\n ) {\n } else {\n for (let j = 1; j < left.length; j++) {\n left1 = left.slice(0, j);\n left2 = left.slice(j);\n if (\n (left1.length >= 2 && left1.startsWith("0")) || //\n (left2.length >= 2 && left2.endsWith("0")) || //\n +left2 === 0\n ) {\n } else {\n A.push("(" + left1 + "." + left2 + ", " + right1 + "." + right2 + ")");\n }\n }\n }\n }\n }\n\n return [...new Set(A)];\n };\n\n----\n\nAfter merging loops into another ( `left` into `left & right`, and `right` into `right & left`)\n\n var ambiguousCoordinates = function (s) {\n let n = s.length;\n\n // answer array\n let A = [];\n\n // remove ( and ), reduce length by 2\n s = s.slice(1, n - 1);\n n -= 2;\n\n for (let i = 1; i < n; i++) {\n let left = s.slice(0, i);\n let right = s.slice(i);\n\n // ---------- no decimals\n if (\n (left.length >= 2 && left.startsWith("0")) ||\n (right.length >= 2 && right.startsWith("0"))\n ) {\n } else {\n A.push("(" + left + ", " + right + ")");\n }\n\n // left decimal, then left & right decimal\n for (let j = 1; j < left.length; j++) {\n left1 = left.slice(0, j);\n left2 = left.slice(j);\n if (\n (left1.length >= 2 && left1.startsWith("0")) || //\n (left2.length >= 2 && left2.endsWith("0")) || //\n +left2 === 0\n ) {\n continue;\n }\n\n // ---------- left decimal\n if (right.length >= 2 && right.startsWith("0")) {\n } else {\n A.push("(" + left1 + "." + left2 + ", " + right + ")");\n }\n\n // ---------- left & right decimal\n for (let j = 1; j < right.length; j++) {\n right1 = right.slice(0, j);\n right2 = right.slice(j);\n if (\n (right1.length >= 2 && right1.startsWith("0")) || //\n (right2.length >= 2 && right2.endsWith("0")) || //\n +right2 === 0\n ) {\n continue;\n }\n\n A.push("(" + left1 + "." + left2 + ", " + right1 + "." + right2 + ")"); //prettier-ignore\n }\n }\n\n // right decimal, then right & left decimal\n for (let j = 1; j < right.length; j++) {\n right1 = right.slice(0, j);\n right2 = right.slice(j);\n if (\n (right1.length >= 2 && right1.startsWith("0")) || //\n (right2.length >= 2 && right2.endsWith("0")) || //\n +right2 === 0\n ) {\n continue;\n }\n\n // ---------- right decimal\n if (left.length >= 2 && left.startsWith("0")) {\n } else {\n A.push("(" + left + ", " + right1 + "." + right2 + ")");\n }\n\n // ---------- right & left decimal\n for (let j = 1; j < left.length; j++) {\n left1 = left.slice(0, j);\n left2 = left.slice(j);\n if (\n (left1.length >= 2 && left1.startsWith("0")) || //\n (left2.length >= 2 && left2.endsWith("0")) || //\n +left2 === 0\n ) {\n continue;\n }\n\n A.push("(" + left1 + "." + left2 + ", " + right1 + "." + right2 + ")"); //prettier-ignore\n }\n }\n }\n\n return [...new Set(A)];\n };\n\n----\n | 1 | 0 | ['JavaScript'] | 0 |
ambiguous-coordinates | C++ clean and short codes | c-clean-and-short-codes-by-mkyang-gh5h | \nchar buf[14];\nclass Solution {\npublic:\n inline bool check(const char *c, int n) {\n return 1==n||c[0]!=\'0\'||c[n-1]!=\'0\';\n }\n vector<s | mkyang | NORMAL | 2021-05-13T11:00:38.541174+00:00 | 2021-05-13T11:00:38.541215+00:00 | 65 | false | ```\nchar buf[14];\nclass Solution {\npublic:\n inline bool check(const char *c, int n) {\n return 1==n||c[0]!=\'0\'||c[n-1]!=\'0\';\n }\n vector<string> helper (const char *c, int n) {\n vector<string> ans;\n if(n==1) {\n ans.push_back(string(c, 1));\n return move(ans);\n }\n if(c[0]==\'0\') {\n buf[0]=\'0\';\n buf[1]=\'.\';\n for(int i=1; i<n; ++i) {\n buf[i+1]=c[i];\n }\n buf[n+1]=\'\\0\';\n ans.push_back(buf);\n } else if(c[n-1]==\'0\'){\n ans.push_back(string(c,n));\n } else {\n for(int i=0; i<n; ++i) {\n buf[i]=c[i];\n }\n buf[n]=\'\\0\';\n buf[n+1]=\'\\0\';\n ans.push_back(buf);\n buf[n]=\'.\';\n for(int i=n-1; i>0; --i){\n swap(buf[i], buf[i+1]);\n ans.push_back(buf);\n }\n }\n return move(ans);\n }\n vector<string> ambiguousCoordinates(string s) {\n int N=s.size()-2;\n const char * c =s.c_str()+1;\n string str("(");\n vector<string> ans;\n for(int i=0; i<N-1; ++i) {\n // cout<<string(c, i+1)<<":"<<check(c, i+1)<<" | "\n // <<string(c+i+1, N-i-1)<<":"<<check(c+i+1, N-i-1)<<"\\n";\n if(check(c, i+1) && check(c+i+1, N-i-1)) {\n auto left=helper(c, i+1);\n auto right=helper(c+i+1, N-i-1);\n for(auto &l:left) {\n for(auto &r:right) {\n ans.push_back(str+l+", "+r+")");\n }\n }\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
ambiguous-coordinates | Simple commented code in C++ | simple-commented-code-in-c-by-kanchan191-8ay7 | \nclass Solution {\npublic:\n vector<string>fun(string str)\n {\n vector<string>ans;\n int n = str.length();\n if(n == 1)\n {\ | kanchan19102000 | NORMAL | 2021-05-13T10:13:10.745218+00:00 | 2021-05-13T10:13:10.745250+00:00 | 69 | false | ```\nclass Solution {\npublic:\n vector<string>fun(string str)\n {\n vector<string>ans;\n int n = str.length();\n if(n == 1)\n {\n return {str};\n }\n // cases like "123"\n if(str[0] != \'0\')\n {\n ans.push_back(str);\n }\n \n if(str[0] == \'0\')\n {\n // cases like "0110"\n if(str.back() == \'0\')\n {\n return {};\n }\n // cases like "011"\n return {"0." + str.substr(1)};\n }\n \n // for cases like 123 -- final vector would be {123, 1.23, 12.3}, but\n // for cases like 120 -- final vector would be {120} and not {120, 1.20, 12.0} as 1.20 and 12.0 are invalid \n if(str.back() != \'0\')\n {\n for(int i = 1; i < n; i++)\n {\n string first = str.substr(0, i);\n string second = str.substr(i);\n ans.push_back(first + "." + second);\n } \n }\n return ans;\n }\n vector<string> ambiguousCoordinates(string s) \n {\n vector<string>ans;\n // removing parenthesis\n string str = s.substr(1, s.length() - 2);\n int n = str.length();\n \n for(int i = 1; i < n; i++)\n {\n string first = str.substr(0, i);\n string second = str.substr(i);\n \n vector<string>for_first = fun(first);\n vector<string>for_second = fun(second);\n \n for(int i = 0; i < for_first.size(); i++)\n {\n for(int j = 0; j < for_second.size(); j++)\n {\n ans.push_back("(" + for_first[i] + ", " + for_second[j] + ")");\n }\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
ambiguous-coordinates | Python3 straightforward solution - Ambiguous Coordinates | python3-straightforward-solution-ambiguo-f5f5 | \nclass Solution:\n def ambiguousCoordinates(self, S: str) -> List[str]:\n S = S[1:-1]\n def numbers(s):\n ans = []\n for | r0bertz | NORMAL | 2020-10-10T01:54:37.461146+00:00 | 2020-10-10T01:54:37.461176+00:00 | 288 | false | ```\nclass Solution:\n def ambiguousCoordinates(self, S: str) -> List[str]:\n S = S[1:-1]\n def numbers(s):\n ans = []\n for i in range(1, len(s)+1):\n ns = s[:i]\n if s[i:]:\n ns += "." + s[i:]\n if len(ns) > 1 and (\n ns[0] == \'0\' and ns[-1] == \'0\' or\n ns[0] == \'0\' and ns[1] != \'.\' or\n ns[-1] == \'0\' and \'.\' in ns):\n continue\n ans.append(ns) \n return ans \n return [\'(\' + p[0] + \', \' + p[1] + \')\'\n for i in range(1, len(S))\n for p in itertools.product(numbers(S[:i]), numbers(S[i:]))]\n``` | 1 | 0 | ['Python', 'Python3'] | 0 |
ambiguous-coordinates | C++ Easy Solution Explained | c-easy-solution-explained-by-shaunblaze2-k0ix | The idea is very simple. We continuously split the substring in 2 parts. One is our x coordinate the other is y coordinate. Now the helper function finds the nu | shaunblaze21 | NORMAL | 2020-07-30T10:44:08.355791+00:00 | 2020-07-30T10:44:18.463895+00:00 | 261 | false | The idea is very simple. We continuously split the substring in 2 parts. One is our x coordinate the other is y coordinate. Now the helper function finds the number of ways we can form the x coordinate and the y coordinate, we form the final string by combining all x coordinates and y coordinates. Rest of the explanation is in code. Comment for any doubt.\n```\nclass Solution {\npublic:\n vector <string> helper(string s)\n {\n vector <string> v;\n if(s.size()<2)\n return {s};\n int n=s.size();\n if(s[0]==\'0\')\n {\n if(s[n-1]==\'0\')\n return {};\n string t=s.substr(0,1)+ \'.\' + s.substr(1); // if s[0] is 0, only possible solution is 0.xxxxx where last digit!=0\n return {t};\n }\n if(s[n-1]==\'0\')\n return {s}; // if last digit is 0, only possible solution is the string itself\n for(int i=0;i<n-1;i++)\n {\n v.push_back(s.substr(0,i+1)+\'.\'+s.substr(i+1)); // \'.\' in between all substrings\n }\n v.push_back(s);\n return v;\n \n }\n vector<string> ambiguousCoordinates(string S) {\n int n=S.size();\n \n vector <string> ans;\n vector <string> v1,v2;\n for(int i=1;i<n-2;i++)\n {\n v1.clear();\n v2.clear();\n v1= helper(S.substr(1,i));\n v2= helper(S.substr(i+1,n-i-2));\n cout<<S.substr(1,i)<<" "<<S.substr(i+1,n-i-2)<<" ";\n if(v1.empty() || v2.empty())\n continue;\n for(int a=0;a<v1.size();a++)\n {\n for(int b=0;b<v2.size();b++)\n {\n ans.push_back(\'(\'+v1[a]+\',\'+\' \'+v2[b]+\')\');\n }\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
ambiguous-coordinates | Java solution with a simple predicate | java-solution-with-a-simple-predicate-by-suef | \nclass Solution {\n private Predicate<String> coordinatePredicate =\n s -> !(s.contains(".") && s.endsWith("0") || s.startsWith("0") && s.length( | gozakdag | NORMAL | 2020-04-27T23:26:44.196605+00:00 | 2020-04-27T23:26:44.196639+00:00 | 157 | false | ```\nclass Solution {\n private Predicate<String> coordinatePredicate =\n s -> !(s.contains(".") && s.endsWith("0") || s.startsWith("0") && s.length() > 1 && !s.startsWith("0."));\n\n private String removeParentheses(String s) {\n return s.substring(1, s.length() - 1);\n }\n\n public List<String> ambiguousCoordinates(String S) {\n List<String> result = new ArrayList<>();\n S = removeParentheses(S);\n for (int i = 1; i < S.length(); i++) {\n result.addAll(combine(\n possibleCoordinates(S.substring(0, i)),\n possibleCoordinates(S.substring(i))\n ));\n }\n return result;\n }\n\n private List<String> possibleCoordinates(String s) {\n return IntStream.range(0, s.length())\n .mapToObj(i -> insertDot(s, i))\n .filter(coordinatePredicate)\n .collect(Collectors.toList());\n }\n\n private static String insertDot(String val, int place) {\n if (place == 0) {\n return val;\n }\n return val.substring(0, place) + "." + val.substring(place);\n }\n\n private static List<String> combine(List<String> l1, List<String> l2) {\n return l1.stream().flatMap(s1 -> l2.stream().map(s2 -> "(" + s1 + ", " + s2 + ")")).collect(Collectors.toList());\n }\n}\n``` | 1 | 0 | [] | 0 |
ambiguous-coordinates | Python intuitive solution | python-intuitive-solution-by-hongsenyu-3pgh | \n\'\'\'\nSplit the number into left and right halves.\nCompute possible combinations of each half\npick one from left comb and one from right comb to build fin | hongsenyu | NORMAL | 2020-03-28T06:46:35.065569+00:00 | 2020-03-28T06:46:35.065608+00:00 | 188 | false | ```\n\'\'\'\nSplit the number into left and right halves.\nCompute possible combinations of each half\npick one from left comb and one from right comb to build final results.\nwhen build the combinations of a given word, the helper function doesn\'t count invalid numbers.\ntime complexity: O(n*n*n)\nspace: O(n*n)\n\'\'\'\nclass Solution:\n def ambiguousCoordinates(self, S: str) -> List[str]:\n res = []\n len_S = len(S)\n for i in range(2,len_S-1):\n left = S[1:i]\n right = S[i:len_S-1]\n left_comb = self.helper(left)\n right_comb = self.helper(right)\n for l in left_comb:\n for r in right_comb:\n res.append(\'(\'+l+\', \'+r+\')\')\n return res\n \n def helper(self, word):\n if len(word) == 1:\n return [word]\n if word[0] == \'0\':\n if word[-1] != \'0\':\n return [\'0.\'+word[1:]]\n return []\n res = [word]\n if word[-1] != \'0\':\n for i in range(1, len(word)):\n res.append(word[:i]+\'.\'+word[i:])\n return res\n \n``` | 1 | 0 | [] | 0 |
ambiguous-coordinates | C++, easy to understand backtracking idea | c-easy-to-understand-backtracking-idea-b-9xw9 | see inline comments\n\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string S) {\n vector<string> res;\n S = S.substr(1, S.le | mazytes | NORMAL | 2019-04-03T07:48:21.112937+00:00 | 2019-04-03T07:48:21.112999+00:00 | 219 | false | see inline comments\n```\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string S) {\n vector<string> res;\n S = S.substr(1, S.length() - 2);\n dfs(res, S, string(1, S[0]), 1, FIRST);\n return res;\n }\n\nprivate:\n enum STATE {\n FIRST,\n FIRST_PERIOD,\n SECOND,\n SECOND_PERIOD,\n };\n\n void dfs(vector<string>& res, const string& S, string cur, int index, STATE state) {\n // cout<<cur<<" enter"<<endl;\n if (index == S.length()) {\n // cout<<cur<<" final"<<endl;\n if (state == SECOND || (state == SECOND_PERIOD && cur.back() != \'0\')) {\n res.push_back("(" + cur + ")");\n }\n return;\n }\n // avoid leading 0, e.g., "012", afer \'0\' has to put \'.\' or \', \'\n if ((state != FIRST || index != 1 || S[index - 1] != \'0\') && (state != SECOND || cur[cur.length() - 3] != \',\') || S[index - 1] != \'0\') {\n // cout<<cur<<" keep"<<endl;\n dfs(res, S, cur + S[index], index + 1, state);\n }\n // \'.\' can be added at any time if not added yet (will check ending \'0\' of a decimal in two cases: 1) when add a comma, 2) at the end when push into res)\n if (state == FIRST || state == SECOND) {\n // cout<<cur<<" add dot"<<endl;\n dfs(res, S, cur + "." + S[index], index + 1, state == FIRST? FIRST_PERIOD : SECOND_PERIOD);\n }\n // \',\' can be added when if decimal not ended with \'0\'\n if (state == FIRST || (state == FIRST_PERIOD && S[index - 1] != \'0\')) {\n // cout<<cur<<" add comma"<<endl;\n dfs(res, S, cur + ", " + S[index], index + 1, SECOND);\n }\n }\n};\n``` | 1 | 1 | [] | 0 |
ambiguous-coordinates | Kotlin solution | kotlin-solution-by-huangdachuan-2l8f | \nclass Solution {\n fun ambiguousCoordinates(S: String): List<String> {\n val content = S.substring(1, S.length - 1)\n if (content.length <= 1 | huangdachuan | NORMAL | 2018-11-03T03:26:27.031315+00:00 | 2018-11-03T03:26:27.031361+00:00 | 184 | false | ```\nclass Solution {\n fun ambiguousCoordinates(S: String): List<String> {\n val content = S.substring(1, S.length - 1)\n if (content.length <= 1) return listOf()\n return (0 until content.length - 1).flatMap {\n val left = decimals(content.substring(0, it + 1))\n val right = decimals(content.substring(it + 1))\n if (left != null && right != null) {\n left.flatMap { l -> right.map { r -> "($l, $r)"} }\n } else {\n emptyList()\n }\n }\n }\n\n private fun decimals(S: String): List<String>? {\n if (S[0] == \'0\') {\n if (S.length == 1) return listOf("0")\n if (S.all { it == \'0\' }) return null\n if (S.last() == \'0\') return null\n return listOf("0.${S.substring(1)}")\n } else {\n return if (S.last() == \'0\') listOf(S) else (0 until S.length).map {\n if (it < S.length - 1) "${S.substring(0, it + 1)}.${S.substring(it + 1)}" else S\n }\n }\n }\n}\n``` | 1 | 0 | [] | 0 |
ambiguous-coordinates | C++ REAL clear 8ms solution, beats 100%! | c-real-clear-8ms-solution-beats-100-by-m-libk | ```\n vector ambiguousCoordinates(string S) {\n vector res;\n for(int i=1;i<S.size()-2;i++) {\n vector left=makeNum(S.substr(1, i)); | michaelz | NORMAL | 2018-08-10T08:34:32.591961+00:00 | 2018-08-10T08:34:32.592010+00:00 | 374 | false | ```\n vector<string> ambiguousCoordinates(string S) {\n vector<string> res;\n for(int i=1;i<S.size()-2;i++) {\n vector<string> left=makeNum(S.substr(1, i));\n vector<string> right=makeNum(S.substr(i+1, S.size()-2-i));\n for(int m=0;m<left.size();m++) {\n for(int n=0;n<right.size();n++) res.push_back("("+left[m]+", "+right[n]+")");\n }\n }\n return res;\n }\n \n vector<string> makeNum(string num) {\n vector<string> res;\n if(num[0]!=\'0\'||num.size()==1) res.push_back(num);\n for(int i=0;i<num.size()-1;i++) {\n if((num[0]==\'0\'&&i!=0)||num.back()==\'0\') continue;\n res.push_back(num.substr(0, i+1)+"."+num.substr(i+1));\n }\n return res;\n } | 1 | 0 | [] | 1 |
ambiguous-coordinates | Python short & easy to understand solution | python-short-easy-to-understand-solution-hhtl | \nclass Solution:\n def ambiguousCoordinates(self, S):\n def properInt(s):\n return len(s) > 1 and s[0] != "0" or len(s) == 1\n \n | cenkay | NORMAL | 2018-07-28T20:07:56.109405+00:00 | 2018-08-10T08:32:26.901786+00:00 | 206 | false | ```\nclass Solution:\n def ambiguousCoordinates(self, S):\n def properInt(s):\n return len(s) > 1 and s[0] != "0" or len(s) == 1\n \n def properFloat(s, i):\n return s[-1] not in ".0" and properInt(s[:i])\n \n s, res = S[1:-1], set()\n for i in range(len(s)):\n n1, n2 = s[:i + 1], s[i + 1:]\n p1, p2 = properInt(n1), properInt(n2)\n if p1 and p2:\n res.add("({}, {})".format(n1, n2))\n for j in range(len(n1)):\n for k in range(len(n2)):\n n1f = n1[:j + 1] + "." + n1[j + 1:]\n n2f = n2[:k + 1] + "." + n2[k + 1:]\n p1f = properFloat(n1f, j + 1)\n p2f = properFloat(n2f, k + 1)\n if p1f and p2f:\n res.add("({}, {})".format(n1f, n2f))\n if p1f and p2:\n res.add("({}, {})".format(n1f, n2))\n if p1 and p2f:\n res.add("({}, {})".format(n1, n2f))\n return list(res)\n``` | 1 | 1 | [] | 0 |
ambiguous-coordinates | A few solutions | a-few-solutions-by-claytonjwong-0sg1 | May 13th, 2021:\n\nJavascript\n\nlet ambiguousCoordinates = s => {\n let allZeros = s => !_.trim(s, \'0\').length;\n let okStart = s => {\n let t = | claytonjwong | NORMAL | 2018-04-16T21:23:04.283841+00:00 | 2021-05-13T21:04:38.214023+00:00 | 217 | false | **May 13<sup>th</sup>, 2021:**\n\n*Javascript*\n```\nlet ambiguousCoordinates = s => {\n let allZeros = s => !_.trim(s, \'0\').length;\n let okStart = s => {\n let t = _.trimStart(s, \'0\');\n let M = s.length,\n N = t.length\n return M == N || (t[0] == \'.\' && M - 1 == N); // no leading 0s or one leading decimal point 0 (ie: 0.xxx) \n };\n let okEnd = s => {\n let t = _.trimEnd(s, \'0\');\n let M = s.length,\n N = t.length;\n return 0 <= t.indexOf(\'.\') ? M == N : true; // no trailing 0s if decimal exists\n };\n let ok = s => s.length == 1 || (!allZeros(s) && okStart(s) && okEnd(s));\n let decimal = (s, i) => i ? `${s.substring(0, i)}.${s.substring(i, s.length)}` : s;\n let slices = (s, A = []) => {\n let N = s.length - 1, // -1 to ignore \')\'\n i = 1 // +1 to ignore \'(\'\n while (i + 1 < N) {\n // i is the pivot for first, second slices: s[1..i], s[i + 1..N - 1]\n let [ a, b ] = [ s.substring(1, i + 1), s.substring(i + 1, N) ];\n // add decimal points for each j-th index of first and each k-th index of second\n for (let j = 0; j < a.length; ++j) {\n let first = decimal(a, j);\n for (let k = 0; k < b.length; ++k) {\n let second = decimal(b, k);\n if (ok(first) && ok(second))\n A.push([ first, second ]);\n }\n }\n ++i;\n }\n return A; // array of valid slices of s\n }\n return slices(s).map(pair => `(${pair.join(\', \')})`);\n};\n```\n\n---\n\n**August 10<sup>th</sup>, 2018:**\n\nCheck all potential substrings a,b of S. Get potential coordinates for all potential values of a,b and store valid coordinates in vectors cx,cy. Combine all values from cx,cy into the answer to be returned.\n\n*C++*\n```\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string S) {\n vector<string> ans;\n S=S.substr(1,S.size()-2);\n int N=(int)S.size();\n for (int i=1; i<N; ++i){\n string a=S.substr(0,i),b=S.substr(i,N-i);\n vector<string> cx=getCoords(a),cy=getCoords(b);\n for (auto& x: cx)\n for (auto& y: cy)\n ans.push_back("("+x+", "+y+")");\n }\n return ans;\n }\nprivate:\n vector<string> getCoords(const string& s){\n vector<string> coords;\n int N=(int)s.size();\n if (isValid(s)) coords.push_back(s);\n for (int i=1; i<N; ++i){\n string a=s.substr(0,i),b=s.substr(i,N-i),c=(a+"."+b);\n if (isValid(c)) coords.push_back(c);\n }\n return coords;\n }\n bool isValid(const string& s){\n if (s.size() < 2) return true;\n if (s[0]==\'0\' && s[1]!=\'.\') return false;\n if (s.find(\'.\')!=string::npos && s.back()==\'0\') return false;\n return true;\n }\n};\n``` | 1 | 1 | [] | 0 |
ambiguous-coordinates | My c++ solution | my-c-solution-by-0xac-6v9q | \nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string S) {\n vector<string> results;\n string result;\n S = S.substr( | 0xac | NORMAL | 2018-04-15T05:05:35.926001+00:00 | 2018-04-15T05:05:35.926001+00:00 | 128 | false | ```\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string S) {\n vector<string> results;\n string result;\n S = S.substr(1, S.size() - 2);\n for(int i = 1; i < S.size(); ++i)\n {\n string sLeft = S.substr(0, i);\n if (!valid(sLeft)) continue;\n string sRight = S.substr(i);\n if (!valid(sRight)) continue;\n \n for(int k = 0; k < sLeft.size(); ++k)\n {\n if(sLeft[0] == \'0\')\n {\n if(k > 0) break;\n if (sLeft.size() > 1) result = "(" + sLeft.substr(0, 1) + "." + sLeft.substr(1) + ", ";\n else result = "(" + sLeft + ", ";\n }\n else\n {\n if (k && sLeft.back() != \'0\') result = "(" + sLeft.substr(0, k) + "." + sLeft.substr(k) + ", ";\n else if(k < 1) result = "(" + sLeft + ", ";\n else break;\n }\n\n for(int m = 0; m < sRight.size(); ++m)\n {\n if(sRight[0] == \'0\')\n {\n if(m > 0) break;\n if (sRight.size() > 1) results.push_back(result + sRight.substr(0, 1) + "." + sRight.substr(1) + ")");\n else results.push_back(result + sRight + ")");\n }\n else\n {\n if (m && sRight.back() != \'0\') results.push_back(result + sRight.substr(0, m) + "." + sRight.substr(m) +")");\n else if(m < 1) results.push_back(result + sRight + ")");\n else break;\n }\n }\n }\n }\n return results;\n }\n bool valid(string s)\n {\n if (s.size() == 1) return true;\n if (s[0] == \'0\' && s.back() == \'0\') return false;\n return true;\n }\n};\n``` | 1 | 1 | [] | 0 |
ambiguous-coordinates | My Java Solution (39ms) | my-java-solution-39ms-by-silenceleaf-1niq | \n\nclass Solution {\n public List<String> ambiguousCoordinates(String S) {\n char[] array = S.toCharArray();\n int start = 1;\n int end | silenceleaf | NORMAL | 2018-04-15T03:16:20.902112+00:00 | 2018-08-10T08:32:52.703592+00:00 | 217 | false | ```\n\nclass Solution {\n public List<String> ambiguousCoordinates(String S) {\n char[] array = S.toCharArray();\n int start = 1;\n int end = S.length() - 1; // not include\n List<String> result = new ArrayList<>();\n for (int split = start + 1; split < end; split++) {\n for (int j = start - 1; j < split; j++) {\n String validLeft = validNum(array, start, split, j);\n for (int k = split - 1; k < end; k++) {\n String validRight = validNum(array, split, end, k);\n if (validLeft != null && validRight != null)\n result.add("(" + validLeft + ", " + validRight + ")");\n }\n }\n }\n return result;\n }\n \n private String validNum(char[] str, int start, int end, int point) {\n if (point == start - 1) { // means no point\n if (countZero(str, start, end) == str.length)\n return null;\n if (end - start > 1 && str[start] == \'0\')\n return null;\n \n return new String(str, start, end - start);\n } else {\n if (point == start || point == end)\n return null;\n if (point - start > 1 && countZero(str, start, point) == point - start)\n return null;\n if (point - start > 1 && str[start] == \'0\')\n return null;\n if (countZero(str, point, end) == end - point)\n return null;\n if (str[end - 1] == \'0\')\n return null;\n \n return new String(str, start, point - start) + "." + new String(str, point, end - point);\n }\n }\n \n private int countZero(char[] str, int start, int end) {\n int count = 0;\n for (int i = start; i < end; i++) {\n if (str[i] == \'0\')\n count++;\n }\n return count;\n }\n}\n\n``` | 1 | 1 | [] | 0 |
ambiguous-coordinates | C++ Solution with Explanation | c-solution-with-explanation-by-code_repo-29f7 | ````\n#define FORI(s,n) for(int i = s; i < n; i++)\n#define FORJ(s,n) for(int j = s; j < n; j++)\n#define FORK(s,n) for(int k = s; k < n; k++)\n\nclass Solution | code_report | NORMAL | 2018-04-15T03:12:43.935236+00:00 | 2018-08-10T08:33:03.269258+00:00 | 251 | false | ````\n#define FORI(s,n) for(int i = s; i < n; i++)\n#define FORJ(s,n) for(int j = s; j < n; j++)\n#define FORK(s,n) for(int k = s; k < n; k++)\n\nclass Solution {\npublic:\n \n // General idea:\n // 1. Shave off parentheses of S\n // 2. Iterate through index 1 to S.len - 1 (where you can put commas)\n // 3. For each comma position, generate all the possible "numbers" on left and right of comma sepearatly\n // 4. Make sure each "number" is valid:\n // - make sure if decimal exists, number doesn\'t end in zero (A)\n // - make sure if all digits aren\'t zero (B)\n // - make sure if leading digit is zero, next character is a period (C)\n // 5. Once you have a valid numbers on left and right, combine them all\n // 6. Do this for all comma positions, and then put in vector and your done.\n \n bool is_valid (string s) {\n if (s.size () == 1) return true; // check so (C) doesn\'t subscript out of range\n auto is_dec = [](char c) {return c == \'.\';}; // lambda for (A)\n if (any_of (s.begin (), s.end (), is_dec) && s[s.size () - 1] == \'0\') return false; // (A)\n auto is_zero_or_dec = [](char c) { return c == \'0\' || c == \'.\'; }; // lambda for (B)\n if (all_of (s.begin (), s.end (), is_zero_or_dec)) return false; // (B)\n if (s[0] == \'0\') return s[1] == \'.\'; // (C)\n return true;\n }\n \n vector<string> generate (string s) {\n vector<string> a;\n\n if (is_valid (s)) a.push_back (s);\n FORJ (1, s.size ()) {\n string t = s;\n t.insert (j, ".");\n if (is_valid (t)) a.push_back (t);\n }\n \n return a;\n }\n \n vector<string> ambiguousCoordinates(string S) {\n \n S = S.substr (1, S.size () - 2); // shave parantheses\n \n unordered_set<string> u;\n \n FORI (1, S.size ()) {\n \n string x = S.substr (0, i);\n string y = S.substr (i, S.size () - i);\n \n vector<string> a = generate (x); // left of comma \n vector<string> b = generate (y); // right of comma\n \n FORJ (0, a.size ()) {\n FORK (0, b.size ()) {\n u.insert ("(" + a[j] + ", " + b[k] + ")");\n }\n }\n }\n \n vector<string> ans;\n \n for (const auto& e : u) ans.push_back (e);\n \n return ans;\n }\n}; | 1 | 1 | [] | 1 |
ambiguous-coordinates | Simple commented Python Solution | simple-commented-python-solution-by-luck-5gi5 | \nclass Solution:\n def ambiguousCoordinates(self, S):\n \n def possible_val(S):\n ret = set()\n # S itself valid\n | luckypants | NORMAL | 2018-04-15T03:07:19.801747+00:00 | 2018-04-15T03:07:19.801747+00:00 | 176 | false | ```\nclass Solution:\n def ambiguousCoordinates(self, S):\n \n def possible_val(S):\n ret = set()\n # S itself valid\n if S[0]!=\'0\' or len(S)==1:\n ret.add(S)\n for _ in range(1, len(S)):\n left, right = S[:_], S[_:]\n # left of . valid if first char is not \'0\' or its length is just 1\n if len(left)==1 or not left[0]==\'0\':\n # right of . valid if last char is not \'0\'\n if right[-1]!=\'0\':\n ret.add(left+\'.\'+right)\n return ret\n \n # Remove parenthesis\n S = S[1:-1]\n ret = []\n for i in range(1, len(S)):\n # S1: String for first coord, S2: String for second coord\n S1, S2 = S[:i], S[i:]\n # Possible values for S1 and S2\n s1, s2 = possible_val(S1), possible_val(S2)\n if not s1 or not s2: continue\n for c1 in s1:\n for c2 in s2:\n ret.append(\'(\'+c1+\', \'+c2+\')\')\n return ret\n``` | 1 | 1 | [] | 0 |
ambiguous-coordinates | Explained Cpp code | explained-cpp-code-by-aviadblumen-4mzq | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | aviadblumen | NORMAL | 2025-04-10T17:50:36.510994+00:00 | 2025-04-10T17:50:36.510994+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<string> get_all_cords(string s){
vector<string> result;
// ========== integer (no leading zeros) ============
if (! (s.size() > 1 && s[0] == '0'))
result.push_back(s);
// ========= locate decimal point =========
// zeros at the end of decimal point are not allowed
if (s.back() == '0') return result;
// if having a leading zero, allow only 0.XXX decimal point
int max_left_len = (s[0] == '0') ? 1 : s.size()-1;
for(int i = 1; i <= max_left_len; i++){
result.push_back(s.substr(0,i) + "." + s.substr(i));
}
return result;
}
vector<string> ambiguousCoordinates(string s) {
s = s.substr(1,s.size()-2); // remove parentheses
vector<string> result;
// loop over comma position
for(int i=1; i <= s.size()-1; i++){
auto cords_left = get_all_cords(s.substr(0,i));
auto cords_right = get_all_cords(s.substr(i));
for(auto& left : cords_left){
for(auto& right : cords_right){
result.push_back("(" + left + ", " + right + ")");
}
}
}
return result;
}
};
``` | 0 | 0 | ['C++'] | 0 |
ambiguous-coordinates | Ambiguous Coordinates | ambiguous-coordinates-by-ansh1707-tt0m | Complexity
Time complexity: O(N)
Space complexity: O(N)
Code | Ansh1707 | NORMAL | 2025-02-10T16:55:35.973018+00:00 | 2025-02-10T16:55:35.973018+00:00 | 4 | false |
# Complexity
- Time complexity: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python []
class Solution(object):
def ambiguousCoordinates(self, s):
"""
:type s: str
:rtype: List[str]
"""
def generate_numbers(sub):
"""
Generating all valid representations of a number (integer or decimal).
"""
n = len(sub)
if n == 0:
return []
if n == 1 or sub[0] != '0':
results = [sub]
else:
results = []
for i in range(1, n):
left, right = sub[:i], sub[i:]
if (left == "0" or left[0] != "0") and right[-1] != "0":
results.append(left + "." + right)
return results
s = s[1:-1]
n = len(s)
results = []
for i in range(1, n):
left_part = generate_numbers(s[:i])
right_part = generate_numbers(s[i:])
for l in left_part:
for r in right_part:
results.append("(" + l + ", " + r + ")")
return results
``` | 0 | 0 | ['String', 'Backtracking', 'Enumeration', 'Python'] | 0 |
ambiguous-coordinates | Simple Java Solution | simple-java-solution-by-sakshikishore-fzok | Code | sakshikishore | NORMAL | 2025-01-29T12:40:17.428487+00:00 | 2025-01-29T12:40:17.428487+00:00 | 7 | false | # Code
```java []
public class Node
{
String str1,str2;
Boolean dot1=false,dot2=false;
public Node(String s1, String s2, Boolean d1, Boolean d2)
{
str1=s1;
str2=s2;
dot1=d1;
dot2=d2;
}
}
class Solution {
public List<String> ambiguousCoordinates(String s) {
s=s.substring(1,s.length()-1);
String str[]=s.split("");
List<List<Node>> list=new ArrayList();
ArrayList<Node> al=new ArrayList<Node>();
al.add(new Node(str[0],"",false,false));
list.add(al);
for(int i=1;i<str.length;i++)
{
al=new ArrayList<Node>();
String st=str[i];
for(int j=i-1;j>=0;j--)
{
List<Node> l=list.get(j);
for(int p=0;p<l.size();p++)
{
Node node=l.get(p);
if(node.str2.length()==0)
{
if(node.dot1)
{
if(st.length()==1)
{
al.add(new Node(node.str1,st,true,false));
}
else if(st.charAt(0)!='0')
{
al.add(new Node(node.str1,st,true,false));
}
}
else
{
if(st.length()==1)
{
al.add(new Node(node.str1,st,false,false));
}
else if(st.charAt(0)!='0')
{
al.add(new Node(node.str1,st,false,false));
}
if(Integer.parseInt(st)!=0 && st.charAt(st.length()-1)!='0')
{
al.add(new Node(node.str1+"."+st,"",true,false));
}
}
}
else
{
if(!node.dot2)
{
if(Integer.parseInt(st)!=0 && st.charAt(st.length()-1)!='0')
{
al.add(new Node(node.str1,node.str2+"."+st,true,true));
}
}
}
}
st=str[j]+st;
}
if(st.charAt(0)!='0')
{
al.add(new Node(st,"",false,false));
}
list.add(al);
}
List<Node> alist=list.get(list.size()-1);
ArrayList<String> result=new ArrayList<String>();
for(int i=0;i<alist.size();i++)
{
Node node=alist.get(i);
if(node.str2.length()>0)
{
result.add("("+node.str1+", "+node.str2+")");
}
}
return result;
}
}
``` | 0 | 0 | ['Java'] | 0 |
ambiguous-coordinates | go 1.21, clean code | go-121-clean-code-by-colix-ucn8 | null | colix | NORMAL | 2025-01-22T10:25:49.438510+00:00 | 2025-01-22T10:25:49.438510+00:00 | 2 | false | ```golang []
func ambiguousCoordinates(s string) []string {
s = s[1 : len(s)-1]
var ret []string
for i := 1; i < len(s); i++ {
left, right := s[:i], s[i:]
leftParts, rightParts := getValidNumbers(left), getValidNumbers(right)
for _, leftPart := range leftParts {
for _, rightPart := range rightParts {
ret = append(ret, "("+leftPart+", "+rightPart+")")
}
}
}
return ret
}
func getValidNumbers(s string) []string {
if len(s) == 1 {
return []string{s}
}
if s[0] == '0' && s[len(s)-1] == '0' {
return nil
}
if s[0] == '0' {
return []string{"0." + s[1:]}
}
if s[len(s)-1] == '0' {
return []string{s}
}
ret := []string{s}
for i := 1; i < len(s); i++ {
ret = append(ret, s[:i]+"."+s[i:])
}
return ret
}
``` | 0 | 0 | ['Go'] | 0 |
ambiguous-coordinates | 816. Ambiguous Coordinates | 816-ambiguous-coordinates-by-g8xd0qpqty-j7ou | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | G8xd0QPqTy | NORMAL | 2025-01-11T06:20:12.029785+00:00 | 2025-01-11T06:20:12.029785+00:00 | 8 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def ambiguousCoordinates(self, s: str) -> list[str]:
def valid_parts(s):
n = len(s)
if n == 0 or (n > 1 and s[0] == '0' and s[-1] == '0'):
return []
if n > 1 and s[0] == '0':
return [f"0.{s[1:]}"]
res = [s]
for i in range(1, n):
if s[-1] != '0':
res.append(f"{s[:i]}.{s[i:]}")
return res
def make_coordinates(s):
n = len(s)
results = []
for i in range(1, n):
left = valid_parts(s[:i])
right = valid_parts(s[i:])
for l in left:
for r in right:
results.append(f"({l}, {r})")
return results
s = s[1:-1]
return make_coordinates(s)
``` | 0 | 0 | ['Python3'] | 0 |
ambiguous-coordinates | 小筆記 | xiao-bi-ji-by-avisccc-makx | Approach先把它分成兩部份後利用check()各自排列,因為不可以有00.1,1.10等情況所以利用條件事來規避,等兩部分各自排列完成後再利用雙for迴圈來做最後一次排列Code | avisccc | NORMAL | 2025-01-07T02:24:52.547147+00:00 | 2025-01-07T02:24:52.547147+00:00 | 7 | false |
# Approach
<!-- Describe your approach to solving the problem. -->
先把它分成兩部份後利用check()各自排列,因為不可以有00.1,1.10等情況所以利用條件事來規避,等兩部分各自排列完成後再利用雙for迴圈來做最後一次排列
# Code
```cpp []
class Solution {
public:
vector<string> ambiguousCoordinates(string s) {
vector<string> ans;
// 移除括号
s.erase(0, 1); // 删除第一个字符 '('
s.erase(s.size() - 1); // 删除最后一个字符 ')'
int len = s.length();
// 遍历分割点,将字符串分为两部分
for (int i = 1; i < len; i++) {
string n1 = s.substr(0, i); // 左部分
string n2 = s.substr(i); // 右部分
// 检查左右两部分的可能坐标形式
vector<string> part1 = check(n1);
vector<string> part2 = check(n2);
// 组合所有合法的坐标形式
for (const string& p1 : part1) {
for (const string& p2 : part2) {
ans.push_back("(" + p1 + ", " + p2 + ")");
}
}
}
return ans;
}
private:
// 检查字符串是否可以形成合法的数值,并返回所有可能的形式
vector<string> check(const string& s) {
vector<string> results;
// 单一数字直接合法
if (s.length() == 1 || s[0] != '0') {
results.push_back(s);
}
// 添加小数点的合法形式
for (int i = 1; i < s.length(); i++) {
string left = s.substr(0, i);
string right = s.substr(i);
if (left.length() > 1 && left[0] == '0') continue;
// 检查右部分是否合法
if (right.back() == '0') continue;
// 添加合法的小数形式
results.push_back(left + "." + right);
}
return results;
}
};
``` | 0 | 0 | ['C++'] | 0 |
ambiguous-coordinates | Enumeration(Implicit Backtracing) O(n^3) Time Complexity | enumerationimplicit-backtracing-on3-time-yzad | Intuition
Check all possible combinations no need of backtracking.
Complexity
Time complexity: O(n3)
Space complexity: O(n)
Code | yash559 | NORMAL | 2024-12-31T11:19:21.827256+00:00 | 2024-12-31T11:19:21.827256+00:00 | 6 | false | # Intuition
- Check all possible combinations **no need of backtracking.**
# Complexity
- Time complexity: $$O(n^3)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<string> getAllCombos(string &str1, string &str2) {
vector<string> before,after;
int n1 = str1.length();
int n2 = str2.length();
if(to_string(stoll(str1)) == str1) before.push_back(str1);
for(int i = 0;i < n1-1;i++) {
string number = str1.substr(0,i+1);
string decimal = str1.substr(i+1);
if(number[0] == '0' && i > 0) continue;
if(decimal.back() == '0') continue;
before.push_back(number + '.' + decimal);
}
if(to_string(stoll(str2)) == str2) after.push_back(str2);
for(int i = 0;i < n2-1;i++) {
string number = str2.substr(0,i+1);
string decimal = str2.substr(i+1);
//number should not be having leading zeros except single 0
if(number[0] == '0' && i > 0) continue;
//decimal should not be having ending zeros
if(decimal.back() == '0') continue;
after.push_back(number + '.' + decimal);
}
vector<string> combos;
//for two comma separated numbers find all combinations
for(auto &num : before) {
for(auto &deci : after) {
combos.push_back('(' + num + ", " + deci + ')');
}
}
return combos;
}
vector<string> ambiguousCoordinates(string s) {
int n = s.length();
vector<string> res;
for(int i = 1;i < n-2;i++) {
string str1,str2;
//placing comma and removing brackets.
str1 = s.substr(1,i);
str2 = s.substr(i+1);
str2.pop_back();
vector<string> strs = getAllCombos(str1,str2);
for(auto &x : strs) res.push_back(x);
}
return res;
}
};
``` | 0 | 0 | ['C++'] | 0 |
ambiguous-coordinates | My java 8ms solution 53% faster | my-java-8ms-solution-53-faster-by-raghav-khd4 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | raghavrathore7415 | NORMAL | 2024-12-25T11:19:28.554948+00:00 | 2024-12-25T11:19:28.554948+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public List<String> ambiguousCoordinates(String s) {
List<String> res = new ArrayList<>();
getAllComb(s, res);
return res;
}
public void getAllComb(String s, List<String> res){
int n = s.length();
for(int i = 1; i < n - 2; i++){
List<String> left = getCombs(1, i, s);
List<String> right = getCombs(i + 1, n - 2, s);
for(String l : left){
for(String r : right){
res.add("(" + l + ", " + r + ")");
}
}
}
}
public List<String> getCombs(int idx, int eidx, String s){
List<String> res = new ArrayList<>();
if(idx == eidx){
res.add(String.valueOf(s.charAt(idx)));
return res;
}
for(int i = idx + 1; i <= eidx; i++){
String left = s.substring(idx, i);
String right = s.substring(i, eidx + 1);
long nl = Long.parseLong(left);
long nr = Long.parseLong(right);
if(nr % 10 == 0 || (nl == 0 && left.length() > 1)){
break;
}
res.add(left + "." + right);
if(nl == 0){
break;
}
}
String subs = s.substring(idx, eidx + 1);
long val = Long.parseLong(subs);
if(String.valueOf(val).equals(subs)){
res.add(subs);
}
return res;
}
}
``` | 0 | 0 | ['Java'] | 0 |
ambiguous-coordinates | C++ Solution | c-solution-by-hn84de-vztn | Code\ncpp []\nclass Solution {\npublic:\n bool valid(const string& s) {\n if (s.empty()) return false;\n if (s == "0") return true;\n if | hn84de | NORMAL | 2024-12-04T03:49:57.020076+00:00 | 2024-12-04T03:49:57.020102+00:00 | 4 | false | # Code\n```cpp []\nclass Solution {\npublic:\n bool valid(const string& s) {\n if (s.empty()) return false;\n if (s == "0") return true;\n if (s[0] == \'0\') return false;\n return true;\n }\n bool validDecimal(const string& s) {\n bool flag = true;\n for (char c : s) if (c == \'.\') flag = false;\n if (flag) return valid(s);\n if (s.empty()) return false;\n if (s.back() == \'.\' || s.back() == \'0\' || s[0] == \'.\') return false;\n if (s[0] == \'0\' && s[1] != \'.\') return false;\n return true;\n }\n void update(const string& a, const string& b, unordered_set<string>& uset) {\n unordered_set<string> A, B;\n if (valid(a)) A.insert(a);\n if (valid(b)) B.insert(b);\n for (int i = 0; i <= a.size(); i++) {\n string temp = a;\n temp.insert(temp.begin() + i, \'.\');\n if (validDecimal(temp)) A.insert(temp);\n }\n for (int i = 0; i <= b.size(); i++) {\n string temp = b;\n temp.insert(temp.begin() + i, \'.\');\n if (validDecimal(temp)) B.insert(temp);\n }\n for (string aa : A) for (const string pref = "(" + aa + ", "; string bb : B) uset.insert(pref + bb + ")");\n }\n vector<string> ambiguousCoordinates(const string& s) {\n string a = s.substr(1);\n a.pop_back();\n string b;\n for (char c : a) if (c != \' \' && c != \'.\') b += c;\n unordered_set<string> ret;\n for (int i = 0; i < size(b); i++) {\n const string A = string(b.begin(), b.begin() + i);\n const string B = string(b.begin() + i, b.end());\n update(A, B, ret);\n }\n return vector<string>(ret.begin(), ret.end());\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
ambiguous-coordinates | scala list comprehension | scala-list-comprehension-by-vititov-wuq7 | could be improved with memoization\nscala []\nobject Solution {\n def ambiguousCoordinates(s: String): List[String] = {\n val d0 = s.tail.init\n for{\n | vititov | NORMAL | 2024-10-16T20:53:48.205296+00:00 | 2024-10-16T20:53:48.205330+00:00 | 1 | false | could be improved with memoization\n```scala []\nobject Solution {\n def ambiguousCoordinates(s: String): List[String] = {\n val d0 = s.tail.init\n for{\n i0 <- (0 to d0.length).toList\n (t1,d1) = d0.splitAt(i0)\n if t1.length==1 || (t1.length>1 && t1.head != \'0\')\n\n i1 <- (0 to d1.length)\n (t2,d2) = d1.splitAt(i1)\n if !t2.lastOption.contains(\'0\')\n\n i2 <- (0 to d2.length)\n (t3,t4) = d2.splitAt(i2)\n if t3.length==1 || (t3.length > 1 && t3.head != \'0\')\n if !t4.lastOption.contains(\'0\')\n } yield {\n List(List(t1,t2), List(t3,t4))\n .map(_.filter(_.nonEmpty).mkString("."))\n .mkString("(",", ",")")\n }\n }\n}\n``` | 0 | 0 | ['Linked List', 'String', 'Enumeration', 'Scala'] | 0 |
ambiguous-coordinates | Beats 100% time, somehow | beats-100-time-somehow-by-quindecim413-xefa | 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 | quindecim413 | NORMAL | 2024-08-08T19:50:56.579771+00:00 | 2024-08-08T19:50:56.579820+00:00 | 31 | 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$$O(n^3)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n nums = s[1:-1]\n \n def eval_valid(s):\n # print(f\'{s=}\')\n if s[0] == \'0\':\n if len(s) > 1:\n if s[-1] == \'0\':\n return set()\n else:\n return set([f\'0.{s[1:]}\'])\n else:\n return set([\'0\'])\n else:\n produced = set([s])\n \n\n if s[-1] != \'0\':\n for i in range(1, len(s)):\n left = s[:i]\n right = s[i:]\n produced.add(left+\'.\'+right)\n return produced\n\n \n res = []\n \n for i in range(1, len(nums)):\n # print(i)\n start, end = nums[:i], nums[i:]\n # print(start, end)\n\n left_produced = eval_valid(start)\n right_produced = eval_valid(end)\n for left_val in left_produced:\n for right_val in right_produced:\n res.append(f\'({left_val}, {right_val})\')\n return res\n``` | 0 | 0 | ['Python3'] | 0 |
ambiguous-coordinates | JS solution enumeration | js-solution-enumeration-by-siddharthpunt-m0rx | 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 | siddharthpuntambekar | NORMAL | 2024-08-05T05:29:53.487943+00:00 | 2024-08-05T05:29:53.487973+00:00 | 8 | 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 ambiguousCoordinates = function (s) {\n let result = [];\n let enumerate = function (start, end) {\n let res = [];\n let sub = s.substring(start, end);\n if ((parseFloat(sub) + "").length == sub.length) {\n res.push(sub);\n }\n let k = 1;\n let e = sub.length;\n while (k < e) {\n let dec = sub.slice(0, k) + "." + sub.slice(k);\n if ((parseFloat(dec) + "").length == dec.length) {\n res.push(dec);\n }\n k++;\n }\n return res;\n }\n\n for (let i = 2; i < s.length - 1; i++) {\n let res1 = enumerate(1, i);\n let res2 = enumerate(i, s.length - 1);\n if (res1.length && res2.length) {\n res1.forEach(left => res2.forEach(right => result.push("(" + left + ", " + right + ")")));\n }\n }\n return result;\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
ambiguous-coordinates | Java | Backtracking | Explained | java-backtracking-explained-by-prashant4-bwp7 | Idea:\n Consider all possible non-empty breakdowns of s\n Put decimal in both parts in every possible place and check if the output is valid\n If valid, then ad | prashant404 | NORMAL | 2024-07-02T22:27:52.266078+00:00 | 2024-07-02T22:27:52.266111+00:00 | 6 | false | **Idea:**\n* Consider all possible non-empty breakdowns of s\n* Put decimal in both parts in every possible place and check if the output is valid\n* If valid, then add them to the result\n* For validity:\n\t* If a number doesn\'t have a decimal, then it should either be 0 or not have a leading 0\n\t* Else if a number has decimal, then\n\t\t* the whole number part should either be 0 or not have a leading 0\n\t\t* the fraction part mustn\'t have a trailing 0\n>**T/S:** O()/O(), where n = size(s)\n```\nprivate static final String ZERO = "0";\n\npublic List<String> ambiguousCoordinates(String s) {\n\ts = s.substring(1, s.length() - 1);\n\tvar n = s.length();\n\tvar coordinates = new ArrayList<String>();\n\n\tfor (var i = 1; i < n; i++)\n\t\tbacktrack(s.substring(0, i), s.substring(i), coordinates);\n\n\treturn coordinates;\n}\n\nprivate void backtrack(String x, String y, List<String> coordinates) {\n\tvar xCoordinates = putDecimal(x);\n\tvar yCoordinates = putDecimal(y);\n\n\tfor (var xCoordinate : xCoordinates) {\n\t\tif (isInvalid(xCoordinate))\n\t\t\tcontinue;\n\n\t\tfor (var yCoordinate : yCoordinates) {\n\t\t\tif (isInvalid(yCoordinate))\n\t\t\t\tcontinue;\n\t\t\tcoordinates.add("(%s, %s)".formatted(xCoordinate, yCoordinate));\n\t\t}\n\t}\n}\n\nprivate List<String> putDecimal(String s) {\n\tvar decimals = new ArrayList<>(List.of(s));\n\n\tfor (var i = 1; i < s.length(); i++)\n\t\tdecimals.add("%s.%s".formatted(s.substring(0, i), s.substring(i)));\n\n\treturn decimals;\n}\n\nprivate boolean isInvalid(String s) {\n\tvar decimalIndex = s.indexOf(\'.\');\n\n\tif (decimalIndex == -1)\n\t\treturn !s.equals(ZERO) && s.startsWith(ZERO);\n\n\tvar wholePart = s.substring(0, decimalIndex);\n\tif (!wholePart.equals(ZERO) && wholePart.startsWith(ZERO))\n\t\treturn true;\n\n\tvar fractionPart = s.substring(decimalIndex + 1);\n\treturn fractionPart.endsWith(ZERO);\n}\n```\n***Please upvote if this helps*** | 0 | 0 | ['Java'] | 0 |
ambiguous-coordinates | C# Backtracking with Validation Solution | c-backtracking-with-validation-solution-iga6s | Intuition\n Describe your first thoughts on how to solve this problem. To solve the problem of generating all possible original coordinates from a given string | GetRid | NORMAL | 2024-06-27T14:19:02.246940+00:00 | 2024-06-27T14:19:02.246979+00:00 | 18 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->To solve the problem of generating all possible original coordinates from a given string s, we need to explore all ways to split the string into two parts and then generate valid coordinate representations for each part.\n___\n\n# Approach\n<!-- Describe your approach to solving the problem. -->// Extract the Core String: Remove the outer parentheses from the input string s using Substring(1, s.Length - 2).\n\n// Split the String into Two Parts: Iterate through the string to create all possible splits. For each split position i,\n// generate two substrings: the left part and the right part.\n\n// Generate Valid Decima Placements:\n// *For each part, use the GenerateValidNumbers method to generate all valid representations (both integer and decimal) \n// of the substring.\n// *\'IsValidNumber\' checks if the substring is a valid integer (it should not start with \'0\' unless it is exactly "0").\n// *\'IsValidFraction\' checks if the substring can be a valid fraction (it should not end with \'0\').\n\n// Combine the Results: For each valid representation of the left part of each valid represeentation of the right part,\n// combine them to form coordinate pairs and add them to the result list.\n___\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(n^3) where n is the length of the string (excluding parentheses). This is because we generate all possible splits, and for each split, we generate valid decimal representations, which involves checking each substring.\n___\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(n^3), due to the storage required for all possible combinations of valid coordinates.\n___\n\n# Code\n```\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution {\n public IList<string> AmbiguousCoordinates(string s) {\n var result = new List<string>();\n \n // Remove the parentheses\n s = s.Substring(1, s.Length - 2);\n \n for (int i = 1; i < s.Length; i++) {\n var leftParts = GenerateValidNumbers(s.Substring(0, i));\n var rightParts = GenerateValidNumbers(s.Substring(i));\n \n foreach (var left in leftParts) {\n foreach (var right in rightParts) {\n result.Add($"({left}, {right})");\n }\n }\n }\n \n return result;\n }\n \n private IList<string> GenerateValidNumbers(string s) {\n var validNumbers = new List<string>();\n \n if (IsValidNumber(s)) {\n validNumbers.Add(s);\n }\n \n for (int i = 1; i < s.Length; i++) {\n var left = s.Substring(0, i);\n var right = s.Substring(i);\n \n if (IsValidNumber(left) && IsValidFraction(right)) {\n validNumbers.Add($"{left}.{right}");\n }\n }\n \n return validNumbers;\n }\n \n private bool IsValidNumber(string s) {\n // A valid number should not start with \'0\' unless it is exactly "0"\n return !(s.Length > 1 && s[0] == \'0\');\n }\n \n private bool IsValidFraction(string s) {\n // A valid fraction should not end with \'0\'\n return s[s.Length - 1] != \'0\';\n }\n}\n``` | 0 | 0 | ['String', 'Backtracking', 'C#'] | 0 |
ambiguous-coordinates | Simple C++ Solution | simple-c-solution-by-abhishek_499-tst1 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Abhishek_499 | NORMAL | 2024-05-24T19:01:50.954775+00:00 | 2024-05-24T19:01:50.954794+00:00 | 16 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<string> res;\n vector<string> getNums(string s){\n vector<string> result;\n int n=s.size();\n if(n==1)\n return {s};\n\n if(s[0]!=\'0\')\n result.push_back(s);\n\n if(s[0]==\'0\'){\n if(s[n-1]!=\'0\')\n return {"0."+s.substr(1)};\n else\n return {};\n }\n\n for(int i=1;i<n;i++){\n if(s.substr(i).back()==\'0\')\n continue;\n\n auto str=s.substr(0, i)+"."+s.substr(i);\n result.push_back(str);\n }\n\n return result;\n\n\n }\n void helper(string& s){\n\n for(int i=1;i<s.size();i++){\n auto left=getNums(s.substr(0, i));\n auto right=getNums(s.substr(i));\n\n for(auto l:left){\n for(auto r:right){\n res.push_back("("+l+", "+r+")");\n }\n }\n }\n\n \n\n }\n\n vector<string> ambiguousCoordinates(string s) {\n\n s=s.substr(1, s.size()-2);\n helper(s);\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
ambiguous-coordinates | Beats 100% users with rust | beats-100-users-with-rust-by-user0353du-9ueh | 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 | user0353DU | NORMAL | 2024-05-16T08:09:48.725926+00:00 | 2024-05-16T08:09:48.725954+00:00 | 6 | 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\nimpl Solution {\n pub fn ambiguous_coordinates(s: String) -> Vec<String> {\n let mut result: Vec<String> = vec![];\n let mut current: String = String::new();\n Solution::backtrack(&s.chars().collect::<Vec<char>>()[1..s.len() -1].to_vec(), &mut current, false, false,false, &mut result);\n result.into_iter().map(|s| format!("{}{}{}", "(", s, ")")).collect()\n }\n\n pub fn backtrack(items: &Vec<char>,current: &mut String, isCommaAdded: bool,isFirstDotAdded: bool,isSencondDotAdded: bool, result: &mut Vec<String>) {\n if items.len() == 0 {\n if current.contains(\',\') {\n \n \n // check each coordinates for 00, 0.0, etc... \n let parts: Vec<&str> = current.split(\',\').collect();\n \n for part in parts {\n let part = &part.replace(" ", "");\n if part.starts_with("0") && part.len() > 1 && !part.starts_with("0.") || (part.contains(\'.\') && part.ends_with(\'0\')) {\n return;\n } \n } \n result.push(current.clone());\n }\n } else {\n if isCommaAdded {\n if isSencondDotAdded {\n current.push(items[0]); \n Solution::backtrack(&items[1..].to_vec(), current, true, true, true, result);\n current.pop();\n } else {\n current.push(items[0]);\n if items.len() > 1 {\n current.push(\'.\');\n Solution::backtrack(&items[1..].to_vec(), current, true, true, true, result);\n current.pop();\n } \n Solution::backtrack(&items[1..].to_vec(), current, true, true, false, result);\n current.pop();\n }\n } else {\n if isFirstDotAdded {\n current.push(items[0]); \n if items.len() > 1 {\n current.push(\',\');\n current.push(\' \');\n Solution::backtrack(&items[1..].to_vec(), current, true, true, false, result);\n current.pop();\n current.pop();\n }\n Solution::backtrack(&items[1..].to_vec(), current, false, true, false, result);\n current.pop();\n } else {\n if items.len() > 1 {\n current.push(items[0]); \n current.push(\',\');\n current.push(\' \');\n Solution::backtrack(&items[1..].to_vec(), current, true, false, false, result);\n current.pop();\n current.pop();\n current.push(\'.\');\n Solution::backtrack(&items[1..].to_vec(), current, false, true, false, result);\n current.pop();\n Solution::backtrack(&items[1..].to_vec(), current, false, false, false, result);\n current.pop();\n }\n }\n\n }\n }\n }\n}\n``` | 0 | 0 | ['Backtracking', 'Rust'] | 0 |
ambiguous-coordinates | Fast, Simple, Easy to understand, C++ | fast-simple-easy-to-understand-c-by-bilb-wtjw | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires generating all possible ambiguous coordinates from a given string | bilbobilley | NORMAL | 2024-05-06T09:37:41.479073+00:00 | 2024-05-06T09:37:41.479147+00:00 | 14 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires generating all possible ambiguous coordinates from a given string representing a number. Ambiguous coordinates are those that can be interpreted in multiple ways by adding a decimal point at different positions. For example, "123" can be interpreted as "(1, 23)", "(12, 3)", or "(1.2, 3)".\n\nI use this free website to learn C++\nhttps://cppexpert.online/\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe iterate over all possible splits of the input string s into two parts: left and right substrings.\nFor each split, we generate all possible decimal representations for the left and right substrings separately using the populate function.\nWe combine the generated left and right representations to form ambiguous coordinates and add them to the result vector.\nThe populate function generates all possible decimal representations for a given input string.\nIf the input starts with \'0\', it adds the input string itself to the output vector if it has only one digit or adds a decimal representation with the leading zero removed.\nIf the input does not start with \'0\', it adds the input string itself to the output vector and then inserts a decimal point at every position in the string except for the last digit.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nn^2\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nn^2\n# Code\n```\nclass Solution {\npublic:\n\n void populate(const string & in, vector<string>& out) {\n int size_in = in.size();\n if (in.front() == \'0\') {\n if (size_in == 1) {\n out.push_back(in);\n } else {\n if (in.back() == \'0\') {\n // invalid\n } else {\n auto rest = in.substr(1);\n string res = "0.";\n out.push_back(res + rest);\n }\n }\n } else {\n out.push_back(in);\n if (in.back() == \'0\') {\n // invalid\n } else {\n for (int j = 1; j < size_in; j++) {\n string copy_in = in;\n copy_in.insert(j, 1, \'.\');\n out.push_back(copy_in);\n }\n }\n }\n }\n\n vector<string> ambiguousCoordinates(string s) {\n int num_digits = s.size() - 2;\n vector<string> result;\n\n for (int i = 1; i < num_digits; i++) {\n vector<string> lefts;\n vector<string> rights;\n string left = s.substr(1, i);\n string right = s.substr(i + 1, num_digits - i);\n populate(left, lefts);\n populate(right, rights); \n for (const auto & l : lefts) {\n string formatted_l = "(";\n formatted_l += l;\n formatted_l += ", ";\n for (const auto & r : rights) {\n auto formatted_r = r;\n formatted_r.push_back(\')\');\n result.push_back(formatted_l + formatted_r);\n }\n }\n }\n return result;\n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
ambiguous-coordinates | Split at each position and enumerate combinations | split-at-each-position-and-enumerate-com-ns6i | The idea\n1. Split string at each position into 2 parts. e.g. 1234 -> 1|234, 12|34, 123|4\n2. Enumerate positions for .\n\n> How to handle parts?\n\nFor a part | vokasik | NORMAL | 2024-05-06T00:03:31.811783+00:00 | 2024-05-06T00:46:12.431168+00:00 | 20 | false | > The idea\n1. Split string at each position into 2 parts. e.g. `1234 -> 1|234, 12|34, 123|4`\n2. Enumerate positions for `.`\n\n> How to handle parts?\n\nFor a part there are 2 cases:\n1) A string (e.g. `5`, `555`)\nOR\n2) A string with the decimal point (e.g. `5.05`, `50.5`)\n\n> Part validation\n\nEach part needs to be validated based on the case:\n> Validation for 1) A string (e.g. `5`, `555`)\n\nThe part is **invalid** when it starts with `0` and `len(part) > 1`\n\n> Validation for 2) A string with the decimal point (e.g. `5.05`, `50.5`)\n\n1. Split part into **left** and **right**.\nThe **left** part is **invalid** if **left** starts with `0` and `len(left) > 1`\nThe **right** part is **invalid** if **right** ends with `0`\n2. **left** and **right** must be valid to form `x.y` number\n\n> Assemble result\n\nNow that you have valid splits for parts and the parts are valid, all you have to do it enumerate the parts and `connect the dots`:\n```\nfor left_part in left_parts:\n for right_part in right_parts:\n\t {left_part}.{right_part}\n```\n\n```\n def backtrack(i, s, parts):\n for j in range(i, len(s)):\n left = s[i:j]\n right = s[j:]\n if not left and right[0] == \'0\' and len(right) > 1: # skip 0xxx\n continue\n elif left and right[-1] == \'0\': # skip x.xx0\n continue\n elif left and left[0] == \'0\' and len(left) > 1: # skip 0x.xx\n continue\n parts.append(left + (\'.\' if left else \'\') + right)\n return parts\n res = []\n for i in range(2, len(s) - 1):\n for l in backtrack(0, s[1:i], []):\n for r in backtrack(0, s[i:-1], []):\n res.append(f\'({l}, {r})\')\n return res\n``` | 0 | 0 | ['Python', 'Python3'] | 0 |
Subsets and Splits