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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
string-without-aaa-or-bbb | C++ 6 line Easy Code || 100% | c-6-line-easy-code-100-by-code_1501-7awu | *Please upvote me :)*\n\n\n string strWithout3a3b(int A, int B) {\n string res;\n while (A && B) {\n if (A > B) {\n r | code_1501 | NORMAL | 2022-02-28T04:59:58.899557+00:00 | 2022-02-28T04:59:58.899605+00:00 | 902 | false | ****Please upvote me :)****\n\n```\n string strWithout3a3b(int A, int B) {\n string res;\n while (A && B) {\n if (A > B) {\n res += "aab";\n A--;\n } else if (B > A) {\n res += "bba";\n B--;\n } else {\n res += "ab";\n }\n A--;\n B--;\n }\n while (A--) res += "a";\n while (B--) res += "b";\n return res;\n }\n``` | 14 | 0 | ['C'] | 1 |
string-without-aaa-or-bbb | [Java] Simple Greedy | java-simple-greedy-by-gcarrillo-dl9d | \n\nclass Solution {\n public String strWithout3a3b(int A, int B) {\n StringBuilder ans = new StringBuilder();\n int size = A+B;\n int a | gcarrillo | NORMAL | 2019-01-27T04:02:23.046834+00:00 | 2019-01-27T04:02:23.046881+00:00 | 1,163 | false | \n```\nclass Solution {\n public String strWithout3a3b(int A, int B) {\n StringBuilder ans = new StringBuilder();\n int size = A+B;\n int a = 0, b = 0;\n for(int i = 0; i < size; i++){\n if((A >= B && a != 2) || b == 2){ \n ans.append("a");\n A--;\n a++;\n b = 0;\n }else if((B >= A && b != 2) || a == 2) {\n ans.append("b");\n b++;\n B--;\n a = 0;\n }\n \n }\n \n return ans.toString();\n }\n}\n``` | 12 | 1 | [] | 4 |
string-without-aaa-or-bbb | Greedy Approach! || Beats 100%|| C++|| Easy to understand Approach | greedy-approach-beats-100-c-easy-to-unde-eq7j | About the questionThis is a fundamental yet frequently asked problem in FAANG-style interviews. The problem statement indirectly relates to Theory of Computatio | Manthu01 | NORMAL | 2025-03-16T11:21:02.241422+00:00 | 2025-03-16T11:21:02.241422+00:00 | 96 | false | 
# About the question
This is a fundamental yet frequently asked problem in FAANG-style interviews. The problem statement indirectly relates to Theory of Computation (TOC) concepts, so anyone familiar with finite automata and state transitions will have a much clearer visualization of how we are solving it.
# Intuition
At first glance, the problem seems straightforward: avoid $$aaa$$ and $$bbb$$ from appearing in the final string—which is exactly our goal! 😆
However, the real challenge is tracking the counts of $$a$$ and $$b$$ to ensure we don’t exceed the required number of each.
# Approach
We'll maintain a string $$result$$, where we gradually add characters while ensuring no $$aaa$$ or $$bbb$$ forms.
For the approach, we'll be focusing on a greedy approach, which will make a decision based on two things for every iteration we perform to append a particular character
1️⃣ What are the last two characters in the result?
2️⃣ Which character has the higher remaining count?
Every time, we check if the last two characters are same or not. So if they are same, then the next letter we append into the result will be the other character, so as to avoid 3 consecutive same letters ($$aaa$$ or $$bbb$$).
We'll also keep a track of how many $$a's$$ and $$b's$$ are remaining to be appended till now in the string, so that whoever's count is higher, will be added first, when the last two characters are different while checking the condition. This way, the Output string will be having no 3 consecutive $$a's$$ or $$b's$$
# Complexity
- Time complexity:
Since it runs a while loop with a+b iterations, the time complexity is $$O(a+b)$$
- Space complexity:
We're constructing a string of length a+b as output, so the space complexity will be $$O(a+b)$$
# Code
```cpp []
class Solution {
public:
string strWithout3a3b(int a, int b) {
string result;
while (a > 0 || b > 0) {
if (result.size() >= 2 && result.back() == result[result.size() - 2]) {
if (result.back() == 'a') {
result += 'b';
b--;
} else {
result += 'a';
a--;
}
} else {
if (a >= b) {
result += 'a';
a--;
} else {
result += 'b';
b--;
}
}
}
return result;
}
};
```
# Thanks Y'all :)
# Hope this explanation helped! If you found it useful, consider upvoting. Happy coding!🚀 | 11 | 0 | ['String', 'Greedy', 'C++'] | 2 |
string-without-aaa-or-bbb | C++ || Easy to understand || 100% fast✔ | c-easy-to-understand-100-fast-by-nitinsi-fk3s | \n\n# Code\n\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans=""; //String to store the answer\n int counta=0,co | NitinSingh77 | NORMAL | 2023-03-19T13:57:57.738047+00:00 | 2023-03-19T13:57:57.738092+00:00 | 1,153 | false | \n\n# Code\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans=""; //String to store the answer\n int counta=0,countb=0; // Counter to check that a and b should not be greater than two;\n int total=a+b; //No of times the loop will run;\n for(int i=0;i<total;i++)\n {\n if((b>=a && countb<2) || (counta==2 && b>0)) //If b is greater than a and count of b is less than 2 || if count of a ==2 and b is greater than 2 add \'a\';\n {\n ans+=\'b\';\n b--; // decrement given count of b;\n\n countb++; //increment count of b;\n\n counta=0; // make the count of a to 0 , if we don\'t do that then the length of the string will remain 3 because counta<2 || countb<2 condition will never become true after the string size becomes three that\'s why we are making counta=0 and countb=0 in every condition;\n }\n else if((a>=b && counta<2) || (countb==2 && a>0))\n {\n ans+=\'a\';\n a--;\n counta++;\n countb=0;\n }\n }\n return ans; // Return the answer;\n }\n};\n``` | 9 | 0 | ['C++'] | 0 |
string-without-aaa-or-bbb | My Java Solution with the basic idea as comments | my-java-solution-with-the-basic-idea-as-b0g35 | \nclass Solution {\n public String strWithout3a3b(int a, int b) {\n StringBuilder sb = new StringBuilder();\n while (a > 0 || b > 0) {\n | vrohith | NORMAL | 2021-04-25T11:14:48.438369+00:00 | 2021-04-25T11:14:48.438403+00:00 | 1,120 | false | ```\nclass Solution {\n public String strWithout3a3b(int a, int b) {\n StringBuilder sb = new StringBuilder();\n while (a > 0 || b > 0) {\n String s = sb.toString();\n // if we have aa as the last 2 characters, then the next one is b\n if (s.endsWith("aa")) {\n sb.append("b");\n b --;\n }\n // if we have bb as the last 2 characters, then the next one is a\n else if (s.endsWith("bb")) {\n sb.append("a");\n a --;\n }\n // if a > b, append a\n else if (a > b) {\n sb.append("a");\n a --;\n }\n // if b >= a, append b\n else {\n sb.append("b");\n b --;\n }\n }\n return sb.toString();\n }\n}\n``` | 9 | 0 | ['String', 'Java'] | 2 |
string-without-aaa-or-bbb | A simple Java recursion solution | a-simple-java-recursion-solution-by-yili-7sse | \nclass Solution {\n StringBuilder sb = new StringBuilder();\n public String strWithout3a3b(int A, int B) {\n if (A == 0 || B == 0) {\n | yilin_10 | NORMAL | 2019-06-18T17:07:03.643412+00:00 | 2019-06-19T04:39:25.373729+00:00 | 695 | false | ```\nclass Solution {\n StringBuilder sb = new StringBuilder();\n public String strWithout3a3b(int A, int B) {\n if (A == 0 || B == 0) {\n while (A-- > 0) sb.append(\'a\');\n while (B-- > 0) sb.append(\'b\');\n } else if (A == B) {\n sb.append("ab");\n strWithout3a3b(A - 1, B - 1);\n } else if (A > B) { // A > B > 0\n sb.append("aab");\n strWithout3a3b(A - 2, B - 1);\n } else { // B > A > 0\n sb.append("bba");\n strWithout3a3b(A - 1, B - 2);\n }\n return sb.toString();\n }\n}\n``` | 8 | 1 | ['Recursion', 'Java'] | 3 |
string-without-aaa-or-bbb | simple C++ solution 100% faster | simple-c-solution-100-faster-by-anoushka-uh50 | \nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n \n string ans="";\n int ca=0,cb=0; //maintain count of last conti | anoushkas23 | NORMAL | 2021-12-27T14:45:54.831010+00:00 | 2021-12-27T14:45:54.831047+00:00 | 672 | false | ```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n \n string ans="";\n int ca=0,cb=0; //maintain count of last continuously appended a\'s or b\'s\n \n while(a>0 || b>0)\n {\n if(a>=b && ca<2 || (b>=a && cb>=2))\n {\n ans+=\'a\';\n ca++;\n cb=0;\n a--;\n }\n else\n {\n ans+=\'b\';\n cb++;\n ca=0;\n b--;\n }\n }\n return ans;\n }\n};\n``` | 6 | 0 | ['C', 'C++'] | 0 |
string-without-aaa-or-bbb | C++ Simple Logic Best Code :) | c-simple-logic-best-code-by-sayan_11_mai-jz3e | \n\nclass Solution\n{\npublic:\n string strWithout3a3b(int a, int b)\n {\n\n string s;\n if (a > b)\n {\n while (a != 0)\n | sayan_11_maitra | NORMAL | 2022-02-24T17:31:33.545326+00:00 | 2022-02-24T17:31:33.545379+00:00 | 332 | false | ```\n\nclass Solution\n{\npublic:\n string strWithout3a3b(int a, int b)\n {\n\n string s;\n if (a > b)\n {\n while (a != 0)\n {\n s += \'a\';\n a--;\n\n if (a > b)\n {\n s += \'a\';\n a--;\n }\n\n if (b != 0)\n {\n s += \'b\';\n\n b--;\n }\n }\n }\n else if (b > a)\n {\n while (b != 0)\n {\n\n s += \'b\';\n b--;\n if (b > a)\n {\n s += \'b\';\n b--;\n }\n\n if (a != 0)\n {\n s += \'a\';\n\n a--;\n }\n }\n }\n else if (a == b)\n {\n int n = a + b;\n for (int i = 0; i < n / 2; i++)\n {\n s += \'a\';\n s += \'b\';\n }\n }\n return s;\n }\n};\n``` | 5 | 1 | [] | 0 |
string-without-aaa-or-bbb | [C++] Faster Than 100% | Greedy solution | clean and concise | c-faster-than-100-greedy-solution-clean-q689y | Please upvote if it helps!\n\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans="";\n int n=a+b;\n int x=0, | somurogers | NORMAL | 2021-06-22T02:27:15.176686+00:00 | 2021-06-22T02:27:15.176726+00:00 | 382 | false | Please upvote if it helps!\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans="";\n int n=a+b;\n int x=0, y=0;\n for(int i=0;i<n;i++)\n {\n if((a>=b && x!=2) || (y==2 && a>0))\n {\n x++;a--;y=0;\n ans+=\'a\';\n }\n else if((b>=a && y!=2) || (x==2 && b>0))\n {\n y++;b--;x=0;\n ans+=\'b\';\n }\n }\n return ans;\n }\n};\n``` | 5 | 1 | ['Greedy', 'C', 'C++'] | 1 |
string-without-aaa-or-bbb | simple python solution | simple-python-solution-by-ashmit007-3etl | \nclass Solution(object):\n def strWithout3a3b(self, A, B):\n if A == 0 or B == 0:\n return \'a\'*A +\'b\'*B\n elif A>B:\n | ashmit007 | NORMAL | 2019-02-05T11:24:54.284999+00:00 | 2019-02-05T11:24:54.285064+00:00 | 478 | false | ```\nclass Solution(object):\n def strWithout3a3b(self, A, B):\n if A == 0 or B == 0:\n return \'a\'*A +\'b\'*B\n elif A>B:\n return \'aab\' + self.strWithout3a3b(A-2, B-1)\n elif B>A:\n return self.strWithout3a3b(A-1, B-2)+ \'abb\'\n else:\n return \'ab\' * A\n``` | 5 | 0 | [] | 1 |
string-without-aaa-or-bbb | C++ || 100% BEATS | c-100-beats-by-ganeshkumawat8740-68gd | Code\n\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans = "";\n while(a >= 1 && b>=1){\n if(a-b>=1){\ | ganeshkumawat8740 | NORMAL | 2023-06-26T02:53:10.007005+00:00 | 2023-06-26T02:53:10.007025+00:00 | 666 | false | # Code\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans = "";\n while(a >= 1 && b>=1){\n if(a-b>=1){\n ans = ans+"aab";\n a-=2;b--;\n }else if(a==b){\n ans += "ab";\n a--;b--;\n }else{\n ans = ans+"bba";\n a--,b-=2;\n }\n }\n if(a==2)ans += "aa";\n else if(a==1)ans += "a";\n if(b==2)ans += "bb";\n else if(b==1)ans += "b";\n return ans;\n }\n};\n``` | 4 | 0 | ['String', 'Greedy', 'C++'] | 0 |
string-without-aaa-or-bbb | EASY SOLUTION IN JAVA | easy-solution-in-java-by-kumarakash-ae0c | class Solution {\n public String strWithout3a3b(int a, int b) {\n String str="";\n \n while(a!=b)\n {\n if(a> | kumarakash | NORMAL | 2022-08-25T17:57:19.608948+00:00 | 2022-08-25T17:57:19.608991+00:00 | 873 | false | class Solution {\n public String strWithout3a3b(int a, int b) {\n String str="";\n \n while(a!=b)\n {\n if(a>b)\n {\n str=str+"aa";\n str=str+"b";\n a=a-2;\n b--;\n if(b==0||a==0)\n {\n break;\n }\n }\n else if(b>a)\n {\n str=str+"bb";\n str=str+"a";\n b=b-2;\n a--;\n if(b==0||a==0)\n {\n break;\n }\n }\n else\n {\n break;\n }\n }\n if(a==0&&b!=0)\n {\n while(b!=0)\n {\n str=str+"b";\n b--;\n }\n }\n if(a!=0&&b==0)\n {\n while(a!=0)\n {\n str=str+"a";\n a--;\n }\n }\n while(a==b&&(a!=0))\n {\n \n str=str+"a";\n str=str+"b";\n a--;\n b--;\n }\n return str;\n }\n} | 4 | 0 | ['Java'] | 0 |
string-without-aaa-or-bbb | Simple Math Problem Without Recursion | simple-math-problem-without-recursion-by-sbau | This problem can easily be done without recursion.\nSuppose A > B, it can be splitted into two situations.\n1. When A >= 2 * B, the result string can be constru | dentiny | NORMAL | 2019-07-27T15:37:55.478554+00:00 | 2019-07-27T15:37:55.478586+00:00 | 609 | false | This problem can easily be done without recursion.\nSuppose `A > B`, it can be splitted into two situations.\n1. When `A >= 2 * B`, the result string can be constructed with `B "aab"`; since the last character for the current string mush be` \'b\'`, it can be followed with `A - B \'a\'`.\n1. When `B < A < 2 * B`, the result string can be constructed with m `"aab"`, followed be n `"ab"`.\n\nThus two equations can be listed:\n* the number of \'a\': 2 * m + n = A\n* the number of \'b\': m + n = B\n\nThe value of m and n can easily be solved.\n```\nm = A - B\nn = 2 * B - A\n```\n\nHere is my code.\nPython Version\n```\nclass Solution:\n def strWithout3a3b(self, A, B):\n if(B <= A < 2 * B): return "aab" * (A - B) + "ab" * (2 * B - A);\n elif(2 * B <= A <= 2 * B + 2): return "aab" * B + "a" * (A - B * 2);\n elif(A < B < 2 * A): return "bba" * (B - A) + "ba" * (2 * A - B); \n elif(2 * A <= B <= 2 * A + 2): return "bba" * A + "b" * (B - A * 2);\n else: return "";\n```\n\nC++ Version\n```\nclass Solution \n{\nprivate:\n\tstring repearStr(string s, int num)\n\t{\n\t\tstring res = "";\n\t\tfor(int i = 0; i < num; i++) res += s;\n\t\treturn res;\n\t}\n\npublic:\n string strWithout3a3b(int A, int B) \n {\n if(B <= A && A < 2 * B) return repearStr("aab", A - B) + repearStr("ab", 2 * B - A);\n else if(2 * B <= A && A <= 2 * B + 2) return repearStr("aab", B) + repearStr("a", A - B * 2);\n else if(A < B && B < 2 * A) return repearStr("bba", B - A) + repearStr("ba", 2 * A - B);\n else if(2 * A <= B && B <= 2 * A + 2) return repearStr("bba", A) + repearStr("b", B - A * 2);\n else return "";\n }\n};\n```\n\nFeel free to ask any question. : ) | 4 | 1 | ['Math', 'C++', 'Python3'] | 1 |
string-without-aaa-or-bbb | Simple Greedy method(faster than 100.00% of Java online submissions) | simple-greedy-methodfaster-than-10000-of-uswu | Greedy by the number of \'a\' and \'b\';\nRuntime: 3 ms, faster than 100.00% of Java online submissions for String Without AAA or BBB.\n\n\n\nclass Solution {\n | lotay | NORMAL | 2019-03-07T13:59:11.018629+00:00 | 2019-03-07T13:59:11.018661+00:00 | 398 | false | Greedy by the number of \'a\' and \'b\';\nRuntime: 3 ms, faster than 100.00% of Java online submissions for String Without AAA or BBB.\n\n```\n\nclass Solution {\n public String strWithout3a3b(int A, int B) {\n StringBuilder sb = new StringBuilder();\n while(A>B && B > 0){\n sb.append("aab");\n A-=2;\n B--;\n }\n \n while(B>A && A>0) {\n sb.append("bba");\n A--;\n B-=2;\n }\n while (A > 0 && B >0) {\n sb.append("ab");\n A--;\n B--;\n }\n while(A>0){\n sb.append("a");\n A--;\n }\n while(B>0) {\n sb.append("b");\n B--;\n }\n return sb.toString();\n }\n}\n\n``` | 4 | 0 | [] | 0 |
string-without-aaa-or-bbb | String Without AAA or BBB-Easy Python solution beats 96% | string-without-aaa-or-bbb-easy-python-so-3e3x | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | koppuhemanthsaikumar123 | NORMAL | 2025-01-10T04:35:53.940593+00:00 | 2025-01-10T04:35:53.940593+00:00 | 163 | 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
```python []
class Solution(object):
def strWithout3a3b(self, a, b):
"""
:type a: int
:type b: int
:rtype: str
"""
s=''
while a>0 and b>0:
if a==b:
s=s+'a'*1+'b'*1
a=a-1
b=b-1
elif a>b:
s=s+'a'*2+'b'*1
a=a-2
b=b-1
else:
s=s+'b'*2+'a'*1
a=a-1
b=b-2
if a>0:
s=s+'a'*a
elif b>0:
s=s+'b'*b
return s
``` | 3 | 0 | ['String', 'Greedy', 'Python', 'Python3'] | 0 |
string-without-aaa-or-bbb | 0 ms runtime well commented | 0-ms-runtime-well-commented-by-shristha-zgv2 | \n\n# Code\n\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n\n //idea is we count how many continous a\'s & b\'s appended if if b | Shristha | NORMAL | 2023-01-31T15:11:06.076690+00:00 | 2023-01-31T15:11:06.076728+00:00 | 325 | false | \n\n# Code\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n\n //idea is we count how many continous a\'s & b\'s appended if if becomes we change next letter to be appended\n \n string res="";\n int la=0,lb=0;\n while(a>0 || b>0){\n\n if((a>=b && la<2 )||(b>=a && lb==2)){//we will append a if its greater than b & not creating aaa\n res+="a";\n a--;\n la++;\n lb=0;\n }\n else {\n res+="b";\n b--;\n lb++;\n la=0;\n }\n\n }\n return res;\n \n }\n};\n``` | 3 | 0 | ['Greedy', 'C++'] | 0 |
string-without-aaa-or-bbb | faster than 94.02% solutions (one liner easy solution) | faster-than-9402-solutions-one-liner-eas-qlwq | \nclass Solution:\n def strWithout3a3b(self, A: int, B: int) -> str:\n return [\'a\']*A + [\'b\']*B\n | sarthak2000 | NORMAL | 2020-12-02T14:33:00.246971+00:00 | 2020-12-02T14:33:00.247014+00:00 | 128 | false | ```\nclass Solution:\n def strWithout3a3b(self, A: int, B: int) -> str:\n return [\'a\']*A + [\'b\']*B\n``` | 3 | 2 | [] | 0 |
string-without-aaa-or-bbb | Recursive JavaScript Solution | recursive-javascript-solution-by-_kamal_-chmt | \n/**\n * @param {number} A\n * @param {number} B\n * @return {string}\n */\nvar strWithout3a3b = function(A, B) {\n if (A === 0) return "b".repeat(B);\n | _kamal_jain | NORMAL | 2020-08-17T17:29:43.941339+00:00 | 2020-08-17T17:29:43.941388+00:00 | 349 | false | ```\n/**\n * @param {number} A\n * @param {number} B\n * @return {string}\n */\nvar strWithout3a3b = function(A, B) {\n if (A === 0) return "b".repeat(B);\n if (B === 0) return "a".repeat(A);\n if (A === B) return "ab" + strWithout3a3b(A - 1, B - 1);\n if (A > B) return "aab" + strWithout3a3b(A - 2, B - 1);\n return "bba" + strWithout3a3b(A - 1, B - 2);\n};\n\n``` | 3 | 0 | ['Recursion', 'JavaScript'] | 4 |
string-without-aaa-or-bbb | [Python] Very easy 4 line solution without loop and recursion beats 100% | python-very-easy-4-line-solution-without-xe9t | \nclass Solution:\n def strWithout3a3b(self, A, B, a = \'a\', b = \'b\'):\n if A < B:\n A, B = B, A\n a, b = b, a\n retur | asukaev | NORMAL | 2019-02-01T05:34:38.473604+00:00 | 2019-02-01T05:34:38.473674+00:00 | 152 | false | ```\nclass Solution:\n def strWithout3a3b(self, A, B, a = \'a\', b = \'b\'):\n if A < B:\n A, B = B, A\n a, b = b, a\n return ((a + a + b) * (A - B) + (a + b) * (A - 2 * (A - B)))[:A + B]\n``` | 3 | 0 | [] | 0 |
string-without-aaa-or-bbb | Java easy understand with comment | java-easy-understand-with-comment-by-zez-1dj6 | \nclass Solution {\n public String strWithout3a3b(int a, int b) {\n // if a > b, swap a and b\n if (b > a) \n\t\t\treturn helper(a, b);\n | zezecool | NORMAL | 2019-01-27T04:25:32.942861+00:00 | 2019-01-27T04:25:32.942927+00:00 | 239 | false | ```\nclass Solution {\n public String strWithout3a3b(int a, int b) {\n // if a > b, swap a and b\n if (b > a) \n\t\t\treturn helper(a, b);\n \n StringBuilder sb = new StringBuilder();\n // build string like "abababab...."\n while (a > 0 && b > 0) {\n sb.append("ab");\n a--;\n b--;\n }\n int size = sb.length();\n // insert 1 \'a\' before 1 \'b\'\n for (int i = 1; a > 2; i = i + 3) {\n sb.insert(i, "a");\n a--;\n }\n // append last 2 \'a\'\n while (a > 0) {\n sb.append("a");\n a--;\n }\n return sb.toString();\n }\n\tprivate String helper(int a, int b) {\n StringBuilder sb = new StringBuilder();\n\t\tString s = strWithout3a3b(b, a);\n\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\tchar c = s.charAt(i);\n\t\t\tif (c == \'a\') \n\t\t\t\tsb.append(\'b\');\n\t\t\tif (c == \'b\') \n\t\t\t\tsb.append(\'a\');\n\t\t}\n\t\treturn sb.toString();\n\t}\n}\n``` | 3 | 2 | [] | 2 |
string-without-aaa-or-bbb | Python short and readable solution (beats 99%) | python-short-and-readable-solution-beats-4iy4 | Approach\nAdd \'a\' or \'b\' to the solution one character at a time. Favor the character with higher remaining frequency (being careful not to add three equal | mcervera | NORMAL | 2024-03-14T00:36:08.162047+00:00 | 2024-03-14T00:36:08.162076+00:00 | 311 | false | # Approach\nAdd _\'a\'_ or _\'b\'_ to the solution one character at a time. Favor the character with higher remaining frequency (being careful not to add three equal characters in a row).\n\n# Complexity\n- Time complexity: $$O(a + b)$$\n\n- Space complexity: $$O(1)$$ aside from the output itself\n\n# Code\n```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n res = []\n a_in_a_row, b_in_a_row = 0, 0\n for _ in range(a + b):\n if (a > b and a_in_a_row < 2) or b_in_a_row == 2:\n res.append(\'a\')\n a_in_a_row, b_in_a_row = a_in_a_row + 1, 0\n a -= 1\n else:\n res.append(\'b\')\n a_in_a_row, b_in_a_row = 0, b_in_a_row + 1\n b -= 1\n return "".join(res)\n``` | 2 | 0 | ['Python3'] | 0 |
string-without-aaa-or-bbb | 0MS Beats 100% 👍👍Beginner Friendly Recursive Easy to understand | 0ms-beats-100-beginner-friendly-recursiv-y9hn | Intuition\nPlease Upvote if this Find HelpFull\uD83D\uDC4D\uD83D\uDC4D\n\n# Code\n\nclass Solution {\npublic:\n\n void generator(string &arr,int &a,int &b){\ | anmoldau_50 | NORMAL | 2023-04-30T20:26:47.446442+00:00 | 2023-08-06T01:21:52.251526+00:00 | 668 | false | # Intuition\nPlease Upvote if this Find HelpFull\uD83D\uDC4D\uD83D\uDC4D\n\n# Code\n```\nclass Solution {\npublic:\n\n void generator(string &arr,int &a,int &b){\n\n if (a<=0 && b<=0){\n return;\n }\n\n if(a>b){\n if(a>=2){\n arr=arr+"aa";\n a-=2;\n }\n else{\n arr=arr+\'a\';\n a-=1;\n }\n if(b>=1){\n arr=arr+\'b\';\n b-=1;\n }\n \n }\n else if(b>a){\n if(b>=2){\n arr=arr+"bb";\n b-=2;\n }\n else{\n arr=arr+\'b\';\n b-=1;\n }\n if(a>=1){\n arr=arr+\'a\';\n a-=1;\n }\n }\n else{\n arr=arr+\'a\'+\'b\';\n a-=1;\n b-=1;\n }\n generator(arr, a, b);\n }\n \n\n string strWithout3a3b(int a, int b) {\n\n string arr ="";\n generator(arr, a, b);\n return arr;\n \n }\n};\n``` | 2 | 0 | ['String', 'Greedy', 'Recursion', 'C++'] | 0 |
string-without-aaa-or-bbb | GREEDY APPROACH || 0ms || BEATS 100% TIME | greedy-approach-0ms-beats-100-time-by-ar-mp81 | \n\n# Code\n\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n if(a == 0 && b == 0) return "";\n if(a == 0)return b == 2?"bb | aryanguptaaa | NORMAL | 2023-03-28T16:47:01.949869+00:00 | 2023-03-28T16:47:01.949907+00:00 | 436 | false | \n\n# Code\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n if(a == 0 && b == 0) return "";\n if(a == 0)return b == 2?"bb":"b";\n if(b == 0)return a == 2?"aa":"a";\n string ans = "";\n if(a >= 2*b || b >= 2*a){\n if(a>b){\n while(b){\n ans += "aab";\n a -= 2;\n b--;\n }\n while(a){\n ans += "a";\n a--;\n }\n return ans;\n }\n else{\n while(a){\n ans += "bba";\n b -= 2;\n a--;\n }\n while(b){\n ans += "b";\n b--;\n }\n return ans;\n }\n }\n\n if(a>b)return "ab" + strWithout3a3b(a-1,b-1);\n return "ba" + strWithout3a3b(a-1,b-1);\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
string-without-aaa-or-bbb | c++ greedy solution ✔ | c-greedy-solution-by-1911uttam-hevj | \nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans="";\n \n // while both \'a\' and \'b\' are available\n | 1911Uttam | NORMAL | 2023-01-06T11:00:05.289907+00:00 | 2023-01-06T11:00:05.289949+00:00 | 454 | false | ```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans="";\n \n // while both \'a\' and \'b\' are available\n while(a && b){\n if(a>b){ // case 1\n ans+= "aab";\n a-=2;\n b--;\n }\n else if(b>a){ //case 2\n ans+= "bba";\n b-=2;\n a--;\n }\n else{ //case 3\n ans+= "ab";\n a--;\n b--;\n }\n }\n \n // when only \'a\' is available\n while(a){\n ans+="a";\n a--;\n }\n \n // when only \'b\' is available\n while(b){\n ans+= "b";\n b--;\n }\n \n return ans;\n }\n};\n```\n\nif you find this helpful plz upvote | 2 | 0 | ['Greedy', 'C'] | 0 |
string-without-aaa-or-bbb | Python3 🐍 concise solution beats 99% | python3-concise-solution-beats-99-by-avs-i1hj | Code\n\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n res = []\n while a + b > 0:\n if len(res) >= 2 and res[ | avs-abhishek123 | NORMAL | 2022-12-29T02:01:12.267219+00:00 | 2022-12-29T02:01:12.267255+00:00 | 783 | false | # Code\n```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n res = []\n while a + b > 0:\n if len(res) >= 2 and res[-2:] == [\'a\', \'a\']:\n res.append(\'b\')\n b-=1\n elif len(res) >= 2 and res[-2:] == [\'b\', \'b\']:\n res.append(\'a\')\n a-=1\n elif a > b:\n res.append(\'a\')\n a-=1\n else:\n res.append(\'b\')\n b-=1\n \n return \'\'.join(res)\n``` | 2 | 0 | ['Python3'] | 0 |
string-without-aaa-or-bbb | c++ | easy | short | c-easy-short-by-venomhighs7-jemr | \n\n# Code\n\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans;\n int ca=0,cb=0;\n while(a>0 || b>0) {\n | venomhighs7 | NORMAL | 2022-11-13T05:31:55.625571+00:00 | 2022-11-13T05:31:55.625608+00:00 | 1,176 | false | \n\n# Code\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans;\n int ca=0,cb=0;\n while(a>0 || b>0) {\n if(a>b) {\n if(ca==2) {\n b--;\n cb=1;\n ca=0;\n ans+="b";\n }\n else {\n a--;\n ca++;\n cb=0;\n ans+="a";\n }\n }\n else {\n if(cb==2) {\n a--;\n ca=1;\n cb=0;\n ans+="a";\n }\n else {\n b--;\n cb++;\n ca=0;\n ans+="b";\n }\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
string-without-aaa-or-bbb | Easy C++ 100% Faster | easy-c-100-faster-by-absolute-mess-14cu | ```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans;\n int ca=0,cb=0;\n while(a>0 || b>0) {\n | absolute-mess | NORMAL | 2022-10-10T10:25:33.748227+00:00 | 2022-10-10T10:25:33.748248+00:00 | 603 | false | ```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans;\n int ca=0,cb=0;\n while(a>0 || b>0) {\n if(a>b) {\n if(ca==2) {\n b--;\n cb=1;\n ca=0;\n ans+="b";\n }\n else {\n a--;\n ca++;\n cb=0;\n ans+="a";\n }\n }\n else {\n if(cb==2) {\n a--;\n ca=1;\n cb=0;\n ans+="a";\n }\n else {\n b--;\n cb++;\n ca=0;\n ans+="b";\n }\n }\n }\n return ans;\n }\n}; | 2 | 0 | ['C'] | 0 |
string-without-aaa-or-bbb | [Java] Simple recursion | java-simple-recursion-by-mo39-fmbh-ouz3 | Intuition:\n\n- Obviously if a==b just append the mix ab until count gets zero. \n- Then if not equal, let\'s make it equal. So just use one more character of w | mo39-fmbh | NORMAL | 2022-01-05T00:58:35.342671+00:00 | 2022-01-05T01:00:26.460723+00:00 | 139 | false | Intuition:\n\n- Obviously if `a==b` just append the mix `ab` until count gets zero. \n- Then if not equal, let\'s make it equal. So just use one more character of whichever has a larger count.\n\n```\nclass Solution {\n public String strWithout3a3b(int a, int b) {\n if (a == 0 && b == 0) return "";\n if (a == 0) return "b" + strWithout3a3b(a, b - 1);\n if (b == 0) return "a" + strWithout3a3b(a - 1, b);\n if (a == b) return "ab" + strWithout3a3b(a - 1, b - 1);\n if (b > a) return "bba" + strWithout3a3b(a - 1, b - 2);\n // a > b\n return "aab" + strWithout3a3b(a - 2, b - 1); \n }\n}\n``` | 2 | 0 | [] | 1 |
string-without-aaa-or-bbb | Human Readable Explanations - No code | human-readable-explanations-no-code-by-l-r6o9 | The goal is to make a b the same, so we can just apend ababab... to the end of result.\n\n\n(1) if a > b: res += "aab"\n(2) else if b > a: res += "bba"\n(3) els | lilydenris | NORMAL | 2021-08-07T19:21:26.303593+00:00 | 2021-08-07T19:21:26.303631+00:00 | 95 | false | The goal is to make a b the same, so we can just apend ababab... to the end of result.\n\n```\n(1) if a > b: res += "aab"\n(2) else if b > a: res += "bba"\n(3) else : res += "ab" * a\n```\n\nYou might have doubts: what if we have (1) then immediately (2), so we get ```aabbba``` wrong results? \n***No, it is not possbile. After appending "aab", a will be still greater or at least equal to b.***\n\n | 2 | 1 | [] | 0 |
string-without-aaa-or-bbb | Python 99% - Greedy Approach with comments | python-99-greedy-approach-with-comments-b6153 | \n# M1 - longer\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n \n # INIT empty string\n res = ""\n availab | daryllman | NORMAL | 2021-06-24T15:41:32.133307+00:00 | 2021-06-24T15:51:01.794446+00:00 | 469 | false | ```\n# M1 - longer\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n \n # INIT empty string\n res = ""\n available = {\'a\': a, \'b\': b}\n \n # While there are still letters to add\n while a > 0 or b > 0:\n \n currLetter = ""\n \n # Loop through the letters\n for letter, count in available.items():\n \n # CHECK if addition of letter is valid\n if len(res) >= 2 and res[-2:] != letter*2 and available[letter]>0 or len(res)<2 and available[letter]>0:\n # If letter not assigned, add this\n if not currLetter:\n print("if not currLetter", letter)\n currLetter = letter\n \n # ELSE if letter is assigned already, check if current letter is better (larger count) => reassign\n else: \n if available[letter] > available[currLetter]:\n print("reassinged currLetter", letter)\n currLetter = letter\n \n \n # END if we cant find any valid letters\n if not currLetter: \n break\n \n res += currLetter\n available[currLetter] -= 1\n \n # RETURN res\n return res\n\n# M2 - shorter\nclass Solution(object):\n def strWithout3a3b(self, A: int, B: int) -> str:\n ans = []\n\n while A or B:\n # If there is consecutive 2 => need to check if is A or B, so we can avoid\n if len(ans) >= 2 and ans[-1] == ans[-2]:\n writeA = ans[-1] == \'b\' # If is B, we can only add A next\n \n else: # No restriction, add the one with largest count\n writeA = A >= B \n \n # Note: We dont need to check if letter count is 0 \n # because all count will be used in the string (as indicated in question)\n \n if writeA:\n A -= 1\n ans.append(\'a\')\n else:\n B -= 1\n ans.append(\'b\')\n\n return "".join(ans)\n``` | 2 | 0 | ['Greedy', 'Python', 'Python3'] | 0 |
string-without-aaa-or-bbb | C++ simple greedy beats 100% | c-simple-greedy-beats-100-by-spyole97-x2h9 | cases:\n1. a == b: in that case "ababababa" or "babababa" will work depending upon the last character of our string.\n2. a > b or b > a: We have to use up the | spyole97 | NORMAL | 2021-05-12T02:13:07.791033+00:00 | 2021-05-12T02:14:13.143497+00:00 | 125 | false | **cases:**\n1. **a == b**: in that case "ababababa" or "babababa" will work depending upon the last character of our string.\n2. **a > b or b > a**: We have to use up the larger one a bit fast so that they are not left behind without a break like after few steps if a >= 3 and b = 0 then we can not stop "aaa" from happening so we will always add **2 of the larger character and 1 of the smaller character**. \nPlease upvote if ypu liked the answer it will motivate me to write better answers in the future. Thank You \n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string sol = "";\n while(a && b)\n {\n if(a > b)\n {\n sol += "aab";\n a -= 2;\n b -= 1;\n }\n else if (b > a)\n {\n sol += "bba";\n a -= 1;\n b -= 2;\n }\n else if(a == b)\n {\n if( sol == "" || sol[sol.length() - 1] == \'a\')\n {\n for(int i = 0; i < a; i++)\n {\n sol += "ba";\n }\n \n }\n else\n {\n for(int i = 0; i < a; i++)\n {\n sol += "ab";\n }\n }\n a = 0;\n b = 0;\n }\n }\n if(a)\n {\n for(int i = 0; i < a; i++)\n {\n sol += \'a\';\n }\n }\n if(b)\n {\n for(int i = 0; i < b; i++)\n {\n sol += \'b\';\n }\n }\n return sol;\n \n }\n};\n``` | 2 | 0 | [] | 0 |
string-without-aaa-or-bbb | Python, 100% faster | python-100-faster-by-llallo-4dey | \nOkay, the concept is so:\n- we are trying to construct the string with "ababab...abbabbabb..." (assuming that giveb count of "a" is smaller that given count o | llallo | NORMAL | 2021-01-23T04:08:08.892672+00:00 | 2021-02-19T12:21:36.279545+00:00 | 193 | false | \nOkay, the concept is so:\n- we are trying to construct the string with "ababab...abbabbabb..." (assuming that giveb count of "a" is smaller that given count of "b", if not just excahnge them)\n- to do so, we need (say) m number of "ab" pairs and (say) n number of "abb" triples. It means that count of "a" is m+n, count of "b" is m+2n. Rearranging gives m=2*count(a)-count(b); n=count(b)-count(a)\n- but what if 2*count(a)<count(b), then m is negative. No worries, we just add all exceeding "b" at the begining of the string to make somesing like "bbabab...abbabb..."\n- by pigeonhole count(b)<2*count(a)+3, otherwise such S would not exist\n- now, lets proceed with the code:\n\n```\nclass Solution(object):\n def strWithout3a3b(self, a, b):\n """\n :type a: int\n :type b: int\n :rtype: str\n """\n ans=\'\'\n\t\t#first define which letter has larger count\n if a>b:\n l=a #larger count\n s=b #smaller count\n lt=\'a\' #letter with larger count\n st=\'b\' #letter with smaller count\n else: #same but opposite example\n l=b\n s=a\n lt=\'b\'\n st=\'a\'\n if l>2*s: #adding exceed "b" to the begining\n ans+=lt*(l-2*s)\n l=s*2 #after addition count(b)=2*count(a) exactly\n ans+=(st+lt)*(2*s-l)+(st+lt+lt)*(l-s) #just in accordance with the rearengement we did\n return ans\n\t\t\n | 2 | 0 | [] | 1 |
string-without-aaa-or-bbb | [Python], simple, beats 98% | python-simple-beats-98-by-manasswami-nmap | \nclass Solution(object):\n def strWithout3a3b(self, A, B):\n """\n :type A: int\n :type B: int\n :rtype: str\n """\n | manasswami | NORMAL | 2020-05-20T17:05:06.642247+00:00 | 2020-05-20T17:05:06.642335+00:00 | 148 | false | ```\nclass Solution(object):\n def strWithout3a3b(self, A, B):\n """\n :type A: int\n :type B: int\n :rtype: str\n """\n res = ""\n curr = \'a\' if A>B else \'b\'\n while A>0 or B>0:\n if curr == \'a\':\n if A>B and A>1:\n res += "aa"\n A -= 2\n else: \n res+= "a"\n A -= 1\n curr = "b"\n else:\n if B>A and B>1:\n res += "bb"\n B -= 2\n else: \n res+= "b"\n B -= 1\n curr = "a"\n \n return res\n``` | 2 | 0 | [] | 0 |
string-without-aaa-or-bbb | python not fastest but easy to read (36 ms, faster than 73.13%) | python-not-fastest-but-easy-to-read-36-m-6rny | \nclass Solution:\n def strWithout3a3b(self, A: int, B: int) -> str:\n output = ""\n a = 0 # length of last sequence of \'a\'\n b = 0 | talistern21 | NORMAL | 2019-04-25T04:46:41.990624+00:00 | 2019-04-25T04:46:41.990654+00:00 | 300 | false | ```\nclass Solution:\n def strWithout3a3b(self, A: int, B: int) -> str:\n output = ""\n a = 0 # length of last sequence of \'a\'\n b = 0 # length of last sequence of \'b\'\n i = 0\n size = A + B\n \n while i < size:\n if (a < 2 and A > B) or b==2:\n output += \'a\'\n b = 0\n a += 1\n A -= 1\n else: \n output += \'b\'\n b += 1\n a = 0\n B -= 1\n i += 1\n \n return output \n``` | 2 | 0 | ['Python'] | 0 |
string-without-aaa-or-bbb | Python (with explanation) | python-with-explanation-by-frankthecodem-smpd | \nclass Solution(object):\n def strWithout3a3b(self, A, B):\n """\n :type A: int\n :type B: int\n :rtype: str\n """\n | frankthecodemonkey | NORMAL | 2019-02-21T02:43:36.991862+00:00 | 2019-02-21T02:43:36.991905+00:00 | 328 | false | ```\nclass Solution(object):\n def strWithout3a3b(self, A, B):\n """\n :type A: int\n :type B: int\n :rtype: str\n """\n # greedy strategy\n # differ by 2 - take (2,1)\n # differ by 1 - still take(2,1)\n # same - take 1 of each\n \n # we\'ll remove it later\n result = \'a\'\n while A > 0 and B > 0:\n a_part = \'\'\n b_part = \'\'\n if A > B:\n a_part = \'aa\'\n b_part = \'b\'\n elif B > A:\n a_part = \'a\'\n b_part = \'bb\'\n else:\n a_part = \'a\'\n b_part = \'b\'\n \n if result[-1] == \'a\':\n result += b_part + a_part\n else:\n result += a_part + b_part\n \n A -= len(a_part)\n B -= len(b_part)\n \n result = result[1:]\n if A != \'\': \n result = result + A*\'a\' if result[0] == \'a\' else A*\'a\' + result\n if B != \'\':\n result = result + B*\'b\' if result[0] == \'b\' else B*\'b\' + result\n \n return result\n\n```\n\nsince the maximal difference is 3, doing (2,1) will guarantee that A,B will eventually be even | 2 | 0 | [] | 0 |
string-without-aaa-or-bbb | Easy to understand java solution | easy-to-understand-java-solution-by-zzz-ilmg | \npublic String strWithout3a3b(int A, int B) {\n if (A > B) {\n return helper(A, \'a\', B, \'b\');\n }\n return helper(B, \'b\', | zzz_ | NORMAL | 2019-02-20T00:20:39.396114+00:00 | 2019-02-20T00:20:39.396179+00:00 | 230 | false | ```\npublic String strWithout3a3b(int A, int B) {\n if (A > B) {\n return helper(A, \'a\', B, \'b\');\n }\n return helper(B, \'b\', A, \'a\');\n }\n\n private String helper(int ca, char a, int cb, char b) {\n StringBuilder sb = new StringBuilder();\n while (ca-- > 0) {\n sb.append(a);\n if (ca > cb) {\n sb.append(a);\n ca--;\n }\n if (cb-- > 0) {\n sb.append(b);\n }\n }\n return sb.toString();\n }\t\n``` | 2 | 0 | [] | 1 |
string-without-aaa-or-bbb | Java simple recursive solution 4ms beats 99.80% + explanation | java-simple-recursive-solution-4ms-beats-8wcj | The idea is simple:\n1. find max(A,B), and so define MORE and LESS variables\n2. every step we want to decrease the difference MORE-LESS to avoid the case when | olsh | NORMAL | 2019-01-30T22:15:05.341035+00:00 | 2019-01-30T22:15:05.341084+00:00 | 241 | false | The idea is simple:\n1. find max(A,B), and so define MORE and LESS variables\n2. every step we want to decrease the difference MORE-LESS to avoid the case when in the end of the string we have too much same letters. So at the end of algorithm this difference should bw at most = 2.\n3. each letter can repeat contiguonaly at max 2 times -> if we know, that the difference MORE-LESS>2, we write 2 letters responsible for MORE and 1 for LESS number to decrease the difference. !!!WE DON\'T WRITE ONLY "MORE" LETTERS WITHOUT "LESS" LETTERS BECAUSE IF ON THE NEXT ITERATION MORE-LESS>2 AGAIN, WE\'LL HAVE TOO MUCH CONTIGUOUS "MORE" LETTERS (>3).\n4. when MORE-LESS is finally 2 or less, we keep calm and append every letter only once.\n\nThe full code:\n```\nclass Solution {\n public String strWithout3a3b(int A, int B) {\n StringBuilder b = new StringBuilder();\n if (A<B){\n createString(b, A, B, \'a\', \'b\');\n }else {\n createString(b, B, A, \'b\', \'a\');\n }\n return b.toString();\n }\n \n public void createString (StringBuilder b, int less, int more, char l, char m){\n if (more==0) return;\n else if (less==0) {\n b.append(m);\n createString(b,less,more-1,l,m);\n }\n else if (more-less>=3){\n b.append(m).append(m).append(l);\n createString(b,less-1,more-2,l,m);\n }\n else {\n b.append(m).append(l);\n createString(b,less-1,more-1,l,m);\n }\n }\n}\n``` | 2 | 0 | [] | 0 |
string-without-aaa-or-bbb | python solution | python-solution-by-born_2_code-pfq3 | \nclass Solution(object):\n def strWithout3a3b(self, A, B):\n """\n :type A: int\n :type B: int\n :rtype: str\n """\n | born_2_code | NORMAL | 2019-01-29T13:58:38.065823+00:00 | 2019-01-29T13:58:38.065865+00:00 | 138 | false | ```\nclass Solution(object):\n def strWithout3a3b(self, A, B):\n """\n :type A: int\n :type B: int\n :rtype: str\n """\n if A == 0:\n return \'b\' * B\n elif B == 0:\n return \'a\' * A\n elif A == B:\n return \'ab\' + self.strWithout3a3b(A-1, B-1)\n elif A > B:\n return \'aab\' + self.strWithout3a3b(A-2, B-1)\n else:\n return \'bba\' + self.strWithout3a3b(A-1, B-2)\n``` | 2 | 0 | [] | 0 |
string-without-aaa-or-bbb | Python3 short and simple | python3-short-and-simple-by-figonet-3rcw | \nclass Solution:\n def strWithout3a3b(self, A, B):\n ans = [] \n while A and B:\n if A > B:\n ans.append(\'aa | figonet | NORMAL | 2019-01-27T18:48:08.487464+00:00 | 2019-01-27T18:48:08.487527+00:00 | 121 | false | ```\nclass Solution:\n def strWithout3a3b(self, A, B):\n ans = [] \n while A and B:\n if A > B:\n ans.append(\'aab\')\n A, B = A - 2, B - 1\n elif A < B:\n ans.append(\'bba\')\n A, B = A - 1, B - 2\n else:\n ans.append(\'ba\')\n A, B = A - 1, B - 1\n \n ans.append(\'a\' * A)\n ans.append(\'b\' * B)\n return "".join(ans)\n``` | 2 | 1 | [] | 0 |
string-without-aaa-or-bbb | Python 100% using formula | python-100-using-formula-by-anniefromtai-n25d | Assume there will always be more b than a.\nThen the result string would be like the following form - (bb)(abb)(abb)(abb)...(ab)(ab)(ab).\n\nIn conclusion there | anniefromtaiwan | NORMAL | 2019-01-27T07:18:54.035085+00:00 | 2019-01-27T07:18:54.035157+00:00 | 203 | false | Assume there will always be more `b` than `a`.\nThen the result string would be like the following form - `(bb)(abb)(abb)(abb)...(ab)(ab)(ab)`.\n\nIn conclusion there will be three patterns:\n* `bb` - could only appear in the most front of the result string\n* `abb` - assume there are `x` sets of this string (`x>=0`)\n* `ab` - assume there are `y` sets of this string (`y>=0`)\n\nWe could calculate the exact values of `x` and `y`, by listing following linear equations:\n* x + y = a (`a` is equal to the sum of `x` and `y`)\n* 2x + y = b (`b` is equal to the sum of `2x` and `y`, because `b` exists twice in string `x`)\n\nResulting in the final formula:\n* x = b - a\n* y = 2a - b\n\nThen we go to handle the edge case when `bb` is needed in the most front of the string.\nLet\'s say, `a=1, b=4`. Then according to the devised formular `x=3, y=-2`. The negative value of `y` contradicts our basic assumption `y>=0`. (This contradiction means we will need `-2` sets of string `y`(`ab`), which obviously contradicts to the reality.)\nIn conclusion, whevever the values of `x` or `y` are negative, we need to put a set of `bb` in the most front.\n\nSo below is the complete code.\n\n```\ndef strWithout3a3b(self, A, B):\n\t(a, str_a), (b, str_b) = sorted([(A, \'a\'), (B, \'b\')])\n\n\tfront_b = False\n\tif 2*a < b:\n\t\tb -= 2\n\t\tfront_b = True\n\tx = b - a\n\ty = 2*a - b\n\n\tstr_x = str_a + str_b + str_b\n\tstr_y = str_a + str_b\n\tstr_front = (str_b * 2) if (front_b) else \'\'\n\treturn (str_front) + (str_x * x) + (str_y * y)\n``` | 2 | 1 | [] | 0 |
string-without-aaa-or-bbb | Python Solution | python-solution-by-here0007-fzpf | \nclass Solution:\n def strWithout3a3b(self, A, B):\n """\n :type A: int\n :type B: int\n :rtype: str\n """\n\n def | here0007 | NORMAL | 2019-01-27T06:14:35.268500+00:00 | 2019-01-27T06:14:35.268542+00:00 | 114 | false | ```\nclass Solution:\n def strWithout3a3b(self, A, B):\n """\n :type A: int\n :type B: int\n :rtype: str\n """\n\n def rec(A,B):\n if B == 0:\n return a*A\n if A == B:\n return (b+a)*A\n elif A - B >= 2:\n return a*2 + b + rec(A-2,B-1)\n else:\n return a + rec(A-1,B)\n\n a, b = \'a\', \'b\'\n if A < B:\n A, B = B, A\n a, b = \'b\', \'a\'\n return rec(A,B)\n``` | 2 | 1 | [] | 0 |
string-without-aaa-or-bbb | JAVA most straightforward and concise solution with detailed explanation!!! | java-most-straightforward-and-concise-so-he8s | \nclass Solution {\n StringBuilder buffer = new StringBuilder();\n public String strWithout3a3b(int A, int B) {\n \n // swap A and B, so th | computer-man94 | NORMAL | 2019-01-27T04:34:03.811226+00:00 | 2019-01-27T04:34:03.811330+00:00 | 113 | false | ```\nclass Solution {\n StringBuilder buffer = new StringBuilder();\n public String strWithout3a3b(int A, int B) {\n \n // swap A and B, so that A represents the greater number of occurance between A and B, a represents that corresponding letter.\n String a = "a";\n String b = "b";\n if (B > A) {\n int temp = B;\n B = A;\n A = temp;\n a = "b";\n b = "a";\n }\n String end = "";\n\t\t\n // A > 2 * B + 2 there is no solution, when A = 2 * B + 2 means the end must have two consectutive As.\n\t\t// for consistency of code, we just add two \'a\'s to the end in advance. \n\t\t// So that we just need to deal with the case when A <= 2 * B,where we can handle these case by keep adding two patterns \'ab\' and \'aab\'.\n if (A > 2 * B) {\n end = a + a;\n A -= 2;\n }else {\n end = "";\n }\n\n // diminish the gap between A and B until A == B\n while (A != B) {\n if (A > B) {\n buffer.append(a + a + b);\n A -= 2;\n B -= 1;\n }\n }\n \n // on this stage, A = B, so we just add pattern \'ab\'\n while (A > 0) {\n buffer.append(a + b);\n A--;\n B--;\n }\n // add the end;\n buffer.append(end);\n return buffer.toString();\n }\n \n}\n``` | 2 | 2 | [] | 0 |
string-without-aaa-or-bbb | Short and concise solution | short-and-concise-solution-by-yz5548-x72n | \nclass Solution {\n public String strWithout3a3b(int A, int B) {\n StringBuilder sb = new StringBuilder();\n int a = 0, b = 0;\n while( | yz5548 | NORMAL | 2019-01-27T04:24:52.280582+00:00 | 2019-01-27T04:24:52.280645+00:00 | 122 | false | ```\nclass Solution {\n public String strWithout3a3b(int A, int B) {\n StringBuilder sb = new StringBuilder();\n int a = 0, b = 0;\n while(A>0 || B>0){\n if(b<2 && (B-A>1 || a==2 || A==0)){\n sb.append(\'b\');\n B--;b++;\n a=0;\n }else{\n sb.append(\'a\');\n A--;a++;\n b=0;\n }\n }\n return sb.toString();\n }\n}\n``` | 2 | 2 | [] | 0 |
string-without-aaa-or-bbb | 🧩 Greedy String Builder – No "aaa" or "bbb" Allowed! 🚫🔥 | greedy-string-builder-no-aaa-or-bbb-allo-5zzm | IntuitionTo avoid having three consecutive 'a's or 'b's, we need to balance the frequency of both characters carefully.
If one character appears more than the o | aditya7483thakur | NORMAL | 2025-04-10T05:35:13.209366+00:00 | 2025-04-10T05:35:13.209366+00:00 | 8 | false | # Intuition
To avoid having three consecutive 'a's or 'b's, we need to balance the frequency of both characters carefully.
If one character appears more than the other, we can occasionally place two of the more frequent character, followed by one of the other, to prevent violating the "no three consecutive letters" rule.
# Approach
- Use a StringBuilder to construct the result.
- While either a or b is still greater than zero:
- If a > b, we prefer placing "aa" followed by "b" (if b is still available).
- If b > a, we prefer placing "bb" followed by "a" (if a is still available).
- If a == b, we alternate between 'a' and 'b' (since both are balanced).
- This greedy approach makes sure we never add three of the same letter consecutively.
# Complexity
- **Time complexity:**
O(a+b)
We are building a string of length a + b, and each character is appended once.
- **Space complexity:**
O(a+b)
The space is used to store the final result string.
# Code
```java []
class Solution {
public String strWithout3a3b(int a, int b) {
StringBuilder sb = new StringBuilder();
while (a > 0 || b > 0) {
// Choose whether to append 'a' or 'b'
if (a > b) {
if (a >= 2) {
sb.append("aa");
a -= 2;
} else {
sb.append("a");
a--;
}
if (b > 0) {
sb.append("b");
b--;
}
} else if (b > a) {
if (b >= 2) {
sb.append("bb");
b -= 2;
} else {
sb.append("b");
b--;
}
if (a > 0) {
sb.append("a");
a--;
}
} else {
// a == b, alternate them
if (a > 0) {
sb.append("a");
a--;
}
if (b > 0) {
sb.append("b");
b--;
}
}
}
return sb.toString();
}
}
``` | 1 | 0 | ['Java'] | 0 |
string-without-aaa-or-bbb | Easy Approach and Easy to understand(Beat 100%) 😊😊 | easy-approach-and-easy-to-understandbeat-zfnu | Approach and IntuitionThe problem requires constructing a string containing 'a' and 'b' such that no three consecutive 'a's or 'b's appear. Given two integers a | patelaviral | NORMAL | 2025-04-01T05:09:57.791580+00:00 | 2025-04-01T05:09:57.791580+00:00 | 30 | false | # Approach and Intuition
The problem requires constructing a string containing 'a' and 'b' such that no three consecutive 'a's or 'b's appear. Given two integers a and b, representing the count of 'a's and 'b's respectively, we need to construct the longest valid string.
# Intuition
* If a and b are nearly equal, we can alternate 'a' and 'b' ("ababab...").
* If one character count is significantly higher, we must distribute them carefully to avoid consecutive occurrences of three similar letters.
# Approach
1. Handle the case when a > b
* As long as a is much greater than b, add "aa" followed by "bb" if possible.
* When b is exhausted, append remaining 'a's one by one.
2. Handle the case when b > a
* Similarly, add "bb" followed by "aa" if possible.
* When a is exhausted, append remaining 'b's one by one.
3. Handle the case when a == b
* We can safely append alternating "ab" until both are exhausted.
# Time Complexity
* The while-loops iterate at most O(a + b) times, making the time complexity O(a + b).
# Space Complexity
* We store the output in a StringBuilder, resulting in O(a + b) space.
# Example Walkthrough
Example 1
🔹 Input: a = 4, b = 2
🔹 Processing:
* Append "aa" + "b" → "aab"
* Append "aa" + "b" → "aabaab"
* Append remaining "a" → "aabaaba" 🔹 Output: "aabaaba"
Example 2
🔹 Input: a = 3, b = 5
🔹 Processing:
* Append "bb" + "a" → "bba"
* Append "bb" + "a" → "bba bba"
* Append remaining "b" → "bba bba b" 🔹 Output: "bba bba b"
# Code
```java []
class Solution {
public String strWithout3a3b(int a, int b) {
StringBuilder ans = new StringBuilder();
if(a > b){
while(a > 0 && b > 0 && (a/2) < b){
ans.append("aa").append("bb");
b -= 2;
a -= 2;
}
while(b > 0){
ans.append("aa").append("b");
b--;
a -= 2;
}
while(a > 0){
ans.append("a");
a--;
}
}
else if(b > a){
while(b > 0 && a > 0 && (b/2) < a){
ans.append("bb").append("aa");
b -= 2;
a -= 2;
}
while(a > 0){
ans.append("bb").append("a");
b -= 2;
a--;
}
while(b > 0){
ans.append("b");
b--;
}
}
else{
while(b > 0 && a > 0){
ans.append("b").append("a");
b -= 1;
a -= 1;
}
}
return ans.toString();
}
}
``` | 1 | 0 | ['String', 'Greedy', 'Java'] | 0 |
string-without-aaa-or-bbb | String Without AAA or BBB | string-without-aaa-or-bbb-by-ansh1707-rc5v | Code | Ansh1707 | NORMAL | 2025-03-02T23:39:44.488052+00:00 | 2025-03-02T23:39:44.488052+00:00 | 31 | false |
# Code
```python []
class Solution(object):
def strWithout3a3b(self, a, b):
"""
:type a: int
:type b: int
:rtype: str
"""
res = []
while a > 0 or b > 0:
if len(res) >= 2 and res[-1] == res[-2]:
write_a = res[-1] == 'b'
else:
write_a = a >= b
if write_a:
res.append('a')
a -= 1
else:
res.append('b')
b -= 1
return "".join(res)
``` | 1 | 0 | ['String', 'Greedy', 'Python'] | 0 |
string-without-aaa-or-bbb | Easy IF ELSE | easy-if-else-by-madhiarasan-ofam | IntuitionApproachComplexity
Time complexity:O(N)
Space complexity:O(1)
Code | MADHIARASAN | NORMAL | 2025-01-29T08:41:48.865551+00:00 | 2025-01-29T08:41:48.865551+00:00 | 96 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public String strWithout3a3b(int a, int b) {
String ans="";
int ac=0;
int bc=0;
while(a>0 || b>0)
{
if(a>b && ac<2)
{
ans+='a';
ac++;
a--;
bc=0;
}
else if(b>a && bc<2)
{
ans+='b';
bc++;
b--;
ac=0;
}
else if(ac==0 && a>0)
{
ans+='a';
ac++;
bc=0;
a--;
}
else{
ans+='b';
bc++;
ac=0;
b--;
}
}
return ans;
}
}
``` | 1 | 0 | ['Java'] | 0 |
string-without-aaa-or-bbb | Greedy Soln! || Beats 100% || Most Understandable Code! | greedy-soln-beats-100-most-understandabl-973j | Complexity
Time complexity: O(a+b)
Space complexity: O(1)
Code | MandalNitish | NORMAL | 2025-01-10T16:25:11.556911+00:00 | 2025-01-10T16:27:33.704668+00:00 | 114 | false | # Complexity
- Time complexity: O(a+b)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
string strWithout3a3b(int a, int b) {
int s = a+b;
string ans;
int checkA = 0;
int checkB = 0;
for(int i = 0;i<s;i++){
if(b>0 && ((b>=a && checkB <2) || checkA ==2)){
ans+='b';
b--;
checkB++;
checkA =0;
}
else if(a>0 && ((a>=b && checkA<2) || checkB == 2)){
ans+='a';
a--;
checkB = 0;
checkA++;
}
}
return ans;
}
};
``` | 1 | 0 | ['Greedy', 'C++'] | 0 |
string-without-aaa-or-bbb | Beats 100% C++ | beats-100-c-by-nougght-0bp6 | Code | nougght | NORMAL | 2025-01-03T15:29:40.258272+00:00 | 2025-01-03T15:33:34.527290+00:00 | 78 | false |

# Code
```cpp []
class Solution {
public:
string strWithout3a3b(int a, int b) {
string s{" "};
int balance = 0;
char ch;
while (a+b>0)
{
if (b>0 && (a == 0 || b>a && balance < 2 || balance == -2))
{
ch = 'b';
--b;
if (s.back() == ch)
++balance;
else
balance = 1;
}
else if (a>0 && (b == 0 || balance >-2 || balance == 2))
{
ch = 'a';
--a;
if (s.back() == ch)
--balance;
else
balance = -1;
}
s += ch;
}
s.erase(0,1);
return s;
}
};
``` | 1 | 0 | ['String', 'C++'] | 0 |
string-without-aaa-or-bbb | Greedy Solution | greedy-solution-by-vivek_0104-5j6i | IntuitionApproachComplexity
Time complexity:
O(a+b)
Space complexity:
O(a+b)
Code | Vivek_0104 | NORMAL | 2024-12-23T16:27:03.096700+00:00 | 2024-12-23T16:27:03.096700+00:00 | 76 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
- O(a+b)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
- O(a+b)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
string strWithout3a3b(int a, int b) {
string ans;
while(a || b){
bool writeA = false;
int len = ans.size();
if(len>=2 && ans[len-1]==ans[len-2]){
if(ans[len-1]=='b')writeA=true;
}else{
if(a>=b)writeA=true;
}
if(writeA){
ans+='a';
a--;
}else{
ans+='b';
b--;
}
}
return ans;
}
};
``` | 1 | 0 | ['C++'] | 0 |
string-without-aaa-or-bbb | Simple iterative Python solution, beats more than 60% | simple-iterative-python-solution-beats-m-6chu | Intuition\n-We need to produce solution with length of a+b\n-We need to favorize the letter that has a greater value\n\n# Approach\n-Iterate while a and b are n | sdjuric00 | NORMAL | 2024-11-11T22:32:46.443937+00:00 | 2024-11-11T22:32:46.443968+00:00 | 99 | false | # Intuition\n-We need to produce solution with length of a+b\n-We need to favorize the letter that has a greater value\n\n# Approach\n-Iterate while a and b are not used, use list to keep track of letters\n-If last two added letters are the same, add the opposite letter\n\n# Complexity\n- Time complexity: O(a+b)\n\n\n- Space complexity:\nO(a+b)\n\n# Code\n```python3 []\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n # length = a + b\n # num of a \'a\' letters\n # num of b \'b\' letters\n # subsctring aaa and bbb is not occuring in res\n \n res = []\n while a > 0 or b > 0:\n if len(res) >= 2 and res[-1] == res[-2]: # Check last two characters\n if res[-1] == \'a\': # Last two characters are \'a\'\n res.append(\'b\')\n b -= 1\n else: # Last two characters are \'b\'\n res.append(\'a\')\n a -= 1\n else:\n # Prefer adding the letter with the higher count\n if a >= b:\n res.append(\'a\')\n a -= 1\n else:\n res.append(\'b\')\n b -= 1\n \n return "".join(res)\n``` | 1 | 0 | ['String', 'Python3'] | 1 |
string-without-aaa-or-bbb | 0 ms || Beats 100% users || Java | 0-ms-beats-100-users-java-by-gottamharip-xswe | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires generating a string of length a + b such that there are no three c | gottamharipriya | NORMAL | 2024-07-11T19:50:44.322674+00:00 | 2024-07-11T19:50:44.322722+00:00 | 368 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires generating a string of length a + b such that there are no three consecutive \'a\'s or \'b\'s. This can be achieved by alternating between \'a\' and \'b\' characters while ensuring that at no point there are more than two consecutive characters of the same type.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nsolve(a,b,s): This method appends \'b\' and \'a\' alternatively to the result string until both a and b are exhausted.\nDepending on whether a or b is greater, it alternates between appending \'a\' and \'b\' to avoid three consecutive characters of the same type. We make use of variable ac, bc to keep count of a and b appended to the string. After ensuring a and b are balanced, it appends any remaining characters to result string.\n\n# Complexity\n- Time complexity: O(a+b) - This is because each iteration or append operation runs in constant time, and we iterate at most a + b times.\n\n- Space complexity: O(a+b) - This is primarily due used to construct the result string, which grows linearly with the sum of a and b.\n\n# Code\n```\nclass Solution {\n public String solve(int a,int b,String s){\n StringBuilder sb=new StringBuilder(s);\n while(a>0&&b>0){\n sb.append(\'b\');\n sb.append(\'a\');\n a--;\n b--;\n }\n return sb.toString();\n }\n public String strWithout3a3b(int a, int b) {\n StringBuilder sb=new StringBuilder();\n int ac=0,bc=0;\n\n if(a==b)\n return solve(a,b,sb.toString());\n if(a>b){\n while(a>0&&b>0){\n sb.append(\'a\');\n ac++;\n a--;\n if(ac%2==0){\n sb.append(\'b\');\n bc++;\n b--;\n }\n if(a==b){\n return solve(a,b,sb.toString());\n }\n }\n }\n else {\n while(a>0&&b>0){\n sb.append(\'b\');\n bc++;\n b--;\n if(bc%2==0){\n sb.append(\'a\');\n ac++;\n a--;\n }\n if(a==b){\n return solve(a,b,sb.toString());\n }\n }\n }\n\n while(a>0){sb.append(\'a\'); a--;}\n while(b>0){sb.append(\'b\'); b--;}\n return sb.toString();\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
string-without-aaa-or-bbb | Javascript simple solution | javascript-simple-solution-by-gaponov-ko6o | 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 | gaponov | NORMAL | 2024-03-04T12:04:43.787520+00:00 | 2024-03-04T12:04:43.787541+00:00 | 71 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\n/**\n * @param {number} a\n * @param {number} b\n * @return {string}\n */\nvar strWithout3a3b = function(a, b) {\n let s=\'\'\n while(a>0 && b>0) {\n if (a===b) {\n s+=\'ab\'\n a--\n b--\n } else if (a>b) {\n s+=\'aab\'\n a-=2\n b--\n } else if (a<b) {\n s+=\'bba\'\n a--\n b-=2\n }\n }\n if (a>0) s+=\'a\'.repeat(a)\n else if (b>0) s+=\'b\'.repeat(b)\n return s\n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
string-without-aaa-or-bbb | Simple StringBuilder Solution | 100% Beats | simple-stringbuilder-solution-100-beats-8h4al | Intuition\n Describe your first thoughts on how to solve this problem. We want to construct a string with \'a\'s and \'b\'s such that there are no consecutive o | Juyel | NORMAL | 2024-02-29T11:25:06.876560+00:00 | 2024-02-29T11:25:06.876589+00:00 | 49 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->We want to construct a string with \'a\'s and \'b\'s such that there are no consecutive occurrences of more than three \'a\'s or \'b\'s.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* We use a StringBuilder to construct the string.\n* While there are still \'a\'s or \'b\'s remaining, we add characters to the StringBuilder according to the conditions mentioned in the problem.\n# Complexity\n- Time complexity: O(a + b) since we iterate through both a and b.\n\n- Space complexity:O(a + b) for the StringBuilder.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String strWithout3a3b(int a, int b) {\n StringBuilder sb = new StringBuilder();\n while(a > 0 || b > 0) {\n if (a>b && b != 0) {\n sb.append("aab");\n a-=2;\n b--;\n } else if (b > a && a != 0) {\n sb.append("bba");\n b-=2;\n a--;\n } else {\n if (a > 0) {\n sb.append("a");\n a--;\n } else if(b > 0) {\n sb.append("b");\n b--;\n }\n }\n }\n return sb.toString();\n }\n}\n``` | 1 | 0 | ['Greedy', 'Java'] | 0 |
string-without-aaa-or-bbb | Easy C++ solution || Beats 100% | easy-c-solution-beats-100-by-bharathgowd-pnr1 | \n\n# Code\n\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans;\n int n = a + b;\n int i = 0, acount = 0, | bharathgowda29 | NORMAL | 2024-01-02T19:01:45.021368+00:00 | 2024-01-02T19:01:45.021404+00:00 | 552 | false | \n\n# Code\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans;\n int n = a + b;\n int i = 0, acount = 0, bcount = 0;\n while(i < n){\n if(b > a){\n if(bcount < 2 && b > 0){\n ans.push_back(\'b\');\n b--; bcount++;\n acount = 0;\n } \n else if(a > 0 && acount < 2){\n ans.push_back(\'a\');\n a--; acount++;\n bcount = 0;\n }\n i++;\n }\n\n else{\n if(a > 0 && acount < 2){\n ans.push_back(\'a\');\n a--; acount++;\n bcount = 0;\n }\n else if(bcount < 2 && b > 0){\n ans.push_back(\'b\');\n b--; bcount++;\n acount = 0;\n }\n i++;\n }\n }\n\n return ans;\n }\n};\n``` | 1 | 0 | ['String', 'Greedy', 'C++'] | 0 |
string-without-aaa-or-bbb | Beats 100.00% Users||C++ Code||Easy Understandable Solution | beats-10000-usersc-codeeasy-understandab-mvia | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this approach is to iteratively construct a string by adding chara | rashmantri | NORMAL | 2023-08-04T16:57:30.654802+00:00 | 2023-08-04T16:57:30.654825+00:00 | 49 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this approach is to iteratively construct a string by adding characters \'a\' and \'b\' while ensuring that no three consecutive characters are the same.\n\n# Approach\nThe approach involves using two variables a and b to keep track of the remaining counts of characters \'a\' and \'b\'. We start by constructing a temporary string s which holds the current constructed string res. We then check the last two characters of s to decide which character (\'a\' or \'b\') to append next. If the last two characters are \'aa\', we append \'b\' to res and decrement the count of b. If the last two characters are \'bb\', we append \'a\' to res and decrement the count of a. If the counts are not equal, we append the character with the larger count to res and decrement the corresponding count. This ensures that no three consecutive characters are the same. We repeat this process until both a and b become zero.\n\n# Complexity\n- Time complexity: O(max(a, b))\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string res,s="";\n while(a!=0|| b!=0){\n s=res;\n if(s.size()>=2 && s.substr(s.size()-2)=="aa"){\n res+=\'b\';\n b--;\n }\n else if(s.size()>=2 && s.substr(s.size()-2)=="bb"){\n res+=\'a\';\n a--;\n }\n else if(a>b){\n res+=\'a\';\n a--;\n }\n else{\n res+=\'b\';\n b--;\n }\n\n }\n return res;\n \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
string-without-aaa-or-bbb | Solution | solution-by-deleted_user-ehli | C++ []\nclass Solution {\npublic:\n void generator(string &arr,int &a,int &b){\n if (a<=0 && b<=0){\n return;\n }\n if(a>b){\ | deleted_user | NORMAL | 2023-05-17T12:32:25.045198+00:00 | 2023-05-17T13:41:01.159247+00:00 | 662 | false | ```C++ []\nclass Solution {\npublic:\n void generator(string &arr,int &a,int &b){\n if (a<=0 && b<=0){\n return;\n }\n if(a>b){\n if(a>=2){\n arr=arr+"aa";\n a-=2;\n }\n else{\n arr=arr+\'a\';\n a-=1;\n }\n if(b>=1){\n arr=arr+\'b\';\n b-=1;\n }\n }\n else if(b>a){\n if(b>=2){\n arr=arr+"bb";\n b-=2;\n }\n else{\n arr=arr+\'b\';\n b-=1;\n }\n if(a>=1){\n arr=arr+\'a\';\n a-=1;\n }\n }\n else{\n arr=arr+\'a\'+\'b\';\n a-=1;\n b-=1;\n }\n generator(arr, a, b);\n }\n string strWithout3a3b(int a, int b) {\n string arr ="";\n generator(arr, a, b);\n return arr;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n if a == b:\n return "ab" * a\n\n x, y = ("a", "b") if a < b else ("b", "a")\n xc, yc = (a, b) if a < b else (b, a)\n n_yyx = min(xc, yc - xc)\n n_yx = min(xc - n_yyx, yc - 2 * n_yyx)\n nx = xc - n_yyx - n_yx\n ny = yc - 2 * n_yyx - n_yx\n return (y + y + x) * n_yyx + (y + x) * n_yx + y * ny + x * nx\n```\n\n```Java []\nclass Solution {\n public String strWithout3a3b(int A, int B) {\n StringBuilder res = new StringBuilder(A + B);\n char a = \'a\', b = \'b\';\n int i = A, j = B;\n if (B > A) { a = \'b\'; b = \'a\'; i = B; j = A; }\n while (i-- > 0) {\n res.append(a);\n if (i > j) { res.append(a); --i; }\n if (j-- > 0) res.append(b);\n }\n return res.toString();\n }\n}\n```\n | 1 | 0 | ['C++', 'Java', 'Python3'] | 0 |
string-without-aaa-or-bbb | ✔️ Clean and well structured C++ implementation (Top 83.1%) || Easy to understand | clean-and-well-structured-c-implementati-94w8 | This Github repository have solution to every problem I looked for https://github.com/AnasImloul/Leetcode-solutions\nIt is very helpful, check it out.\n\n\nclas | UpperNoot | NORMAL | 2023-03-12T01:26:00.413261+00:00 | 2023-03-12T01:26:00.413293+00:00 | 21 | false | This Github repository have solution to every problem I looked for https://github.com/AnasImloul/Leetcode-solutions\nIt is very helpful, check it out.\n\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans="";\n while(a and b){\n if(a > b) ans += "aab", a--;\n else if(b > a) ans +="bba", b--;\n else ans += "ab";\n a--, b--;\n }\n while(a) ans +=\'a\' , a--;\n while(b) ans +=\'b\' , b--;\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
string-without-aaa-or-bbb | by making count of a and b equal and then removing the higher count character beats 100% | by-making-count-of-a-and-b-equal-and-the-ju9s | \n\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n int ca =0;\n int cb = 0;\n int times = max(a,b);\n \n | rajsiddi | NORMAL | 2023-03-10T11:35:32.257393+00:00 | 2023-03-10T12:13:24.129801+00:00 | 564 | false | \n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n int ca =0;\n int cb = 0;\n int times = max(a,b);\n \n string ans="";\n\n \n\n if(a>b){\n for(int i=0;i<times;i++){\n ans+="ab";\n }\n int bs = abs(b-a);\n // cout<<ans<<endl;\n for(int i=1;i<ans.length();i=i+4){\n ans[i] = \'r\';\n bs--;\n cout<<bs<<" ";\n if(bs == 0){\n break;\n }\n }\n if(bs>0){\n for(int i = ans.length()-1;i>=0;i--){\n if(ans[i] == \'b\'){\n ans[i] = \'r\';\n bs--;\n }\n if(bs == 0){\n break;\n }\n }\n }\n // cout<<ans;\n string temp = "";\n for(int i=0;i<ans.length();i++){\n if(ans[i] == \'r\'){continue;}\n temp+=ans[i];\n }\n ans = temp;\n }else if(b>a){\n for(int i=0;i<times;i++){\n ans+="ba";\n }\n int as = abs(b-a);\n // cout<<ans<<endl;\n for(int i=1;i<ans.length();i=i+4){\n ans[i] = \'r\';\n as--;\n //cout<<as<<" ";\n if(as == 0){\n break;\n }\n }\n if(as>0){\n for(int i = ans.length()-1;i>=0;i--){\n if(ans[i] == \'a\'){\n ans[i] = \'r\';\n as--;\n }\n if(as == 0){\n break;\n }\n }\n }\n // cout<<ans;\n string temp = "";\n for(int i=0;i<ans.length();i++){\n if(ans[i] == \'r\'){continue;}\n temp+=ans[i];\n }\n ans = temp;\n }else{\n for(int i=0;i<times;i++){\n ans+="ab";\n }\n }\n\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
string-without-aaa-or-bbb | Runtime 0ms Beats 100% ✅ || Very easy✅ || Solution C++ | runtime-0ms-beats-100-very-easy-solution-v78c | \n\n# Complexity\n- Time complexity: O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n | Pushkar2111 | NORMAL | 2023-01-04T19:07:50.568068+00:00 | 2023-01-04T19:07:50.568102+00:00 | 59 | false | \n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans="";\n while(a and b){\n if(a > b) ans += "aab", a--;\n else if(b > a) ans +="bba", b--;\n else ans += "ab";\n a--, b--;\n }\n while(a) ans +=\'a\' , a--;\n while(b) ans +=\'b\' , b--;\n return ans;\n }\n};\n``` | 1 | 0 | ['Greedy', 'C++'] | 0 |
string-without-aaa-or-bbb | 1ms java easy | 1ms-java-easy-by-soqi2001-0sft | ``` \npublic String strWithout3a3b(int a, int b) {\n\t\t//\u53BB\u6389\u591A\u4F59\n StringBuilder sb = new StringBuilder();\n while(a > 0 && b > | soqi2001 | NORMAL | 2022-11-14T11:13:17.702547+00:00 | 2022-11-14T11:13:17.702583+00:00 | 118 | false | ``` \npublic String strWithout3a3b(int a, int b) {\n\t\t//\u53BB\u6389\u591A\u4F59\n StringBuilder sb = new StringBuilder();\n while(a > 0 && b > 0){\n if(a > b){\n a -= 2;\n b--;\n sb.append("aab");\n }else if(a == b){\n a--;\n b--;\n sb.append("ab");\n }else if(a < b){\n a--;\n b -= 2;\n sb.append("bba");\n }\n }\n // \u5BF9\u5355\u4E2A\u8FDB\u884C\u78BE\u538B\n while(a > 0){\n a--;\n sb.append("a");\n }\n while(b > 0){\n b--;\n sb.append("b");\n }\n return new String(sb);\n } | 1 | 0 | ['String', 'Java'] | 0 |
string-without-aaa-or-bbb | 3MS EASY TO UNDERSTAND RECURSION SOLUTION | 3ms-easy-to-understand-recursion-solutio-pcsg | \t\n\tclass Solution {\npublic:\n string ans = "";\n void solve(int a,int b){\n if(a<0 || b<0 || (a==0 && b==0))return ;\n if(a-b>=2){\n | abhay_12345 | NORMAL | 2022-11-11T16:22:22.823561+00:00 | 2022-11-11T16:22:22.823605+00:00 | 819 | false | \t```\n\tclass Solution {\npublic:\n string ans = "";\n void solve(int a,int b){\n if(a<0 || b<0 || (a==0 && b==0))return ;\n if(a-b>=2){\n if(b>0){\n ans = ans + "aab";\n solve(a-2,b-1);}else{\n ans = ans + "aa";\n solve(a-2,b);\n }\n }else if(b-a>=2){\n \n if(a>0){ans = ans + "bba";\n solve(a-1,b-2);}else{\n ans = ans + "bb";\n solve(a,b-2);\n }\n }else if(a>b){\n ans = ans + \'a\';\n solve(a-1,b);\n }else if(a<b){\n ans = ans + \'b\';\n solve(a,b-1);\n }else{\n ans = ans + "ab";\n solve(a-1,b-1);\n }\n }\n string strWithout3a3b(int a, int b) {\n ans = "";\n solve(a,b);\n return ans;\n }\n};\n``` | 1 | 1 | ['Greedy', 'Recursion', 'C', 'C++'] | 0 |
string-without-aaa-or-bbb | just check last two chars and append the different one to break the trio | just-check-last-two-chars-and-append-the-qykd | \nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n \n string res = "";\n while(a>0 or b>0)\n {\n if | mr_stark | NORMAL | 2022-08-22T18:56:26.956339+00:00 | 2022-08-22T18:56:26.956377+00:00 | 21 | false | ```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n \n string res = "";\n while(a>0 or b>0)\n {\n if(b>0 && res.size()>=2 && res[res.size()-1] !=\'b\' && res[res.size()-2] !=\'b\')\n {\n res+=\'b\';\n b--;\n }\n else if(a>0 && res.size()>=2 && res[res.size()-1] !=\'a\' && res[res.size()-2] !=\'a\')\n {\n res+=\'a\';\n a--;\n }\n else if(a>b && a>0)\n {\n res+=\'a\';\n a--;\n }\n else if(b>0)\n {\n b--;\n res+=\'b\';\n }\n \n }\n return res;\n \n \n }\n};\n``` | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | Python || Greedy || O(N)->TC || O(N)->SC(for returning result) | python-greedy-on-tc-on-scfor-returning-r-aox6 | Simple algo:\n1. add \'a\' to res if a>b else add \'b\'\n2. if we had used \'aa\' then add \'b\' and vice versa\n\'\'\'\n\n\t\tclass Solution:\n\t\tdef strWitho | ak_guy | NORMAL | 2022-07-28T10:32:04.583531+00:00 | 2022-07-28T10:32:39.324920+00:00 | 112 | false | Simple algo:\n1. add \'a\' to res if a>b else add \'b\'\n2. if we had used \'aa\' then add \'b\' and vice versa\n\'\'\'\n\n\t\tclass Solution:\n\t\tdef strWithout3a3b(self, a: int, b: int) -> str:\n\t\t\tres = ""\n\n\t\t\twhile a > 0 or b > 0:\n\t\t\t\tif len(res) > 1 and res[-1] == res[-2] == \'a\':\n\t\t\t\t\tres += \'b\'\n\t\t\t\t\tb -= 1\n\t\t\t\telif len(res) > 1 and res[-1] == res[-2] == \'b\':\n\t\t\t\t\tres += \'a\'\n\t\t\t\t\ta -= 1\n\t\t\t\telif a > b:\n\t\t\t\t\tres += \'a\'\n\t\t\t\t\ta -= 1\n\t\t\t\telse: \n\t\t\t\t\tres += \'b\'\n\t\t\t\t\tb -= 1\n\n\t\t\treturn res\n\'\'\' | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | Simple and Elegant C++ Solution with Explanation | simple-and-elegant-c-solution-with-expla-95ur | Consider the Below Example:\n\n\nWe now know that we gotta start with the character with the higher frequency.\n\n\nWhat did we understand from the last example | imanshul | NORMAL | 2022-07-08T17:56:35.396306+00:00 | 2022-07-08T22:15:31.589927+00:00 | 268 | false | **Consider the Below Example:**\n\n\n**We now know that we gotta start with the character with the higher frequency.**\n\n\n**What did we understand from the last example?**\nWe not only have to consider the character with higher frequency first, but also have to make sure that we keep sandwiching the char with lower frequency once to maximize the appearance of the character with higher frequency.\n\n**The Code:**\n\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n int n = a + b;\n string ans = "";\n //I\'m making a priority queue just because I don\'t wanna worry about all the if and else.\n priority_queue<pair<int, char>>q;\n\n q.push({a, \'a\'});\n q.push({b, \'b\'});\n\n auto cur = q.top(); //now the cur will contain the char with highest freq.\n q.pop();\n auto prev = q.top();\n q.pop();\n\n while (ans.size() < n) {\n //The below condition decides whether or not to add the cur element twice,\n //i.e. if the cur element\'s frequency is greater than the prev, we will append it one more time.\n if (cur.first > 0 && cur.first > prev.first) {\n ans += cur.second;\n --cur.first;\n }\n if (cur.first > 0) { //otherwise we\'ll add it just one time, i.e. sandwich it between\n ans += cur.second;\n --cur.first;\n }\n swap(cur, prev);\n\n }\n return ans;\n }\n# };\n```\n\n**Follow-up problems:**\n[Leetcode 1405: Longest Happy String](http://leetcode.com/problems/longest-happy-string/)\n[Leetcode 767: Reorganize String](http://leetcode.com/problems/reorganize-string/) | 1 | 0 | ['C', 'C++'] | 0 |
string-without-aaa-or-bbb | Go solution using strings.Builder (0ms) | go-solution-using-stringsbuilder-0ms-by-n5ccc | \nfunc strWithout3a3b(a int, b int) string {\n\tvar sb strings.Builder\n\tsb.Grow(a + b)\n\n\tfor a > 0 || b > 0 {\n\t\tswitch {\n\t\tcase a == 0:\n\t\t\tsb.Wri | superpolikow | NORMAL | 2022-07-06T22:42:39.427602+00:00 | 2022-07-06T22:42:39.427640+00:00 | 38 | false | ```\nfunc strWithout3a3b(a int, b int) string {\n\tvar sb strings.Builder\n\tsb.Grow(a + b)\n\n\tfor a > 0 || b > 0 {\n\t\tswitch {\n\t\tcase a == 0:\n\t\t\tsb.WriteByte(\'b\')\n\t\t\tb--\n\n\t\tcase b == 0:\n\t\t\tsb.WriteByte(\'a\')\n\t\t\ta--\n\n\t\tcase a > b:\n\t\t\tsb.WriteByte(\'a\')\n\t\t\ta--\n\t\t\tsb.WriteByte(\'a\')\n\t\t\ta--\n\t\t\tsb.WriteByte(\'b\')\n\t\t\tb--\n\n\t\tcase b > a:\n\t\t\tsb.WriteByte(\'b\')\n\t\t\tb--\n\t\t\tsb.WriteByte(\'b\')\n\t\t\tb--\n\t\t\tsb.WriteByte(\'a\')\n\t\t\ta--\n\n\t\tdefault:\n\t\t\tsb.WriteByte(\'a\')\n\t\t\ta--\n\t\t\tsb.WriteByte(\'b\')\n\t\t\tb--\n\t\t}\n\t}\n\treturn sb.String()\n}\n```\n | 1 | 0 | ['Go'] | 0 |
string-without-aaa-or-bbb | C++ solution. || Sort of greedy approach. | c-solution-sort-of-greedy-approach-by-sa-bmoy | You may wanna check out 1054. Distant barcodes.\n\n\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans = "";\n int | samarthya2912 | NORMAL | 2022-03-22T13:42:28.554102+00:00 | 2022-03-22T13:43:35.302219+00:00 | 51 | false | You may wanna check out ***1054. Distant barcodes.***\n\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n string ans = "";\n int a_streak = 0, b_streak = 0;\n while(a or b) {\n if(b == 0 or b_streak == 2 or (a > b and a_streak < 2)) {\n ans += \'a\';\n a--;\n a_streak++;\n b_streak = 0;\n }\n else {\n ans += \'b\';\n b--;\n b_streak++;\n a_streak = 0;\n }\n }\n \n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | c++ greedy | c-greedy-by-vicky_therock9-0qwv | \nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n int ca=0,cb=0;\n string ans="";\n while(a>0||b>0){\n if | vicky_therock9 | NORMAL | 2022-03-02T05:18:46.942087+00:00 | 2022-03-02T05:18:46.942135+00:00 | 127 | false | ```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n int ca=0,cb=0;\n string ans="";\n while(a>0||b>0){\n if(a>=b&&ca!=2||cb==2){\n ans+=\'a\';\n ca++;\n a--;\n cb=0;\n }\n else if(b>a&&cb<2||ca==2){\n ans+=\'b\';\n cb++;\n b--;\n ca=0;\n }\n }\n return ans;\n \n }\n};\n``` | 1 | 0 | ['Greedy', 'C'] | 0 |
string-without-aaa-or-bbb | JavaScript Solution - Greedy Approach | javascript-solution-greedy-approach-by-d-r6pa | The way I solved this problem was thinking about which letter we want to prioritize at each point. If the last two consecutive letters were a mixture of "ab" or | Deadication | NORMAL | 2022-02-06T20:22:55.799721+00:00 | 2022-02-06T20:25:44.630253+00:00 | 154 | false | The way I solved this problem was thinking about which letter we want to prioritize at each point. If the last two consecutive letters were a mixture of "ab" or "ba", then we want to use up the letter we have more. However, if the last two letters were "aa", then we would need to use "b" here because of the constraint of no "aaa". This applies to "bb" also. I used two additional variables to count the consecutive letters and reset them as needed.\n\n```\nvar strWithout3a3b = function(a, b) {\n const n = a + b;\n \n let consecutiveAs = 0;\n let consecutiveBs = 0;\n \n let res = "";\n \n for (let i = 0; i < n; i++) {\n if (consecutiveAs < 2 && consecutiveBs < 2) {\n if (a > b) {\n res += "a";\n consecutiveAs++;\n a--;\n consecutiveBs = 0;\n }\n else {\n res += "b";\n consecutiveBs++;\n b--;\n consecutiveAs = 0;\n }\n }\n else if (consecutiveAs == 2) {\n res += "b";\n consecutiveBs++;\n b--;\n consecutiveAs = 0;\n }\n else {\n res += "a";\n consecutiveAs++;\n a--;\n consecutiveBs = 0;\n }\n }\n \n return res;\n}; \n``` | 1 | 0 | ['Greedy', 'JavaScript'] | 0 |
string-without-aaa-or-bbb | Python beats 91% | python-beats-91-by-leopardcoderd-ee6m | \nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n res = []\n while a + b > 0:\n if len(res) >= 2 and res[-2:] = | leopardcoderd | NORMAL | 2022-01-30T00:53:36.516376+00:00 | 2022-01-30T00:53:36.516417+00:00 | 291 | false | ```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n res = []\n while a + b > 0:\n if len(res) >= 2 and res[-2:] == [\'a\', \'a\']:\n res.append(\'b\')\n b-=1\n elif len(res) >= 2 and res[-2:] == [\'b\', \'b\']:\n res.append(\'a\')\n a-=1\n elif a > b:\n res.append(\'a\')\n a-=1\n else:\n res.append(\'b\')\n b-=1\n \n return \'\'.join(res)\n``` | 1 | 0 | ['Python', 'Python3'] | 2 |
string-without-aaa-or-bbb | Super simple java solution - straightforward | super-simple-java-solution-straightforwa-jfe3 | \nclass Solution {\n \n public String strWithout3a3b(int a, int b) {\n StringBuilder str = new StringBuilder();\n int size = a + b;\n | rakshaa | NORMAL | 2022-01-01T02:05:05.454985+00:00 | 2022-01-01T02:05:05.455016+00:00 | 80 | false | ```\nclass Solution {\n \n public String strWithout3a3b(int a, int b) {\n StringBuilder str = new StringBuilder();\n int size = a + b;\n int A =0, B = 0;\n \n for(int i =0;i<size;i++) {\n if(a >=b && A != 2 || a > 0 && B==2) {\n str.append(\'a\');\n A++;\n a--;\n B = 0; \n }\n else if(b >= a && B != 2 || b > 0 && A==2) {\n str.append(\'b\');\n B++;\n b--;\n A = 0; \n }\n }\n return new String(str);\n \n }\n}\n``` | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | C++|| Greedy || Beats 100% | c-greedy-beats-100-by-gnitish31-nf59 | \nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n int m;\n m=max(a,b);\n string s="";\n if(m==a){\n | gnitish31 | NORMAL | 2021-11-01T10:25:36.410201+00:00 | 2021-11-01T10:26:02.119388+00:00 | 68 | false | ```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n int m;\n m=max(a,b);\n string s="";\n if(m==a){\n while(a && b && a>b){\n if(a>1){\n s+="aa";\n a--;\n }\n else{\n s+="a";\n }\n a--;\n s+="b";\n \n b--;\n }\n \n while(a && b){\n s+="ab";\n a--;b--;\n }\n while(a){\n s+="a";\n a--;\n }\n while(b){\n s+="b";\n b--;\n }\n \n }\n else{\n while(a && b && a<b){\n \n if(b>1){\n s+="bb";\n b--;\n }\n else{\n s+="b";\n }\n b--;\n s+="a";\n \n a--;\n }\n while(a && b){\n s+="ab";\n a--;b--;\n }\n while(b ){\n s+="b";\n b--;\n }\n while(a){\n s+="a";\n a--;\n }\n }\n return s;\n \n \n }\n};\n``` | 1 | 0 | ['String', 'Greedy'] | 0 |
string-without-aaa-or-bbb | C++ Simple || 100 % Faster || Greedy || With Comments | c-simple-100-faster-greedy-with-comments-u0me | There can be 3 sitautions a>b, b>a and a=b;\nas we need to avoid three a and b so we greedly doing the following:-\nif(a>b) res.append("aab")\nif(b>a) res.appen | shantys | NORMAL | 2021-08-20T11:50:17.307993+00:00 | 2021-08-20T11:50:17.308034+00:00 | 137 | false | There can be 3 sitautions a>b, b>a and a=b;\nas we need to avoid three a and b so we greedly doing the following:-\nif(a>b) res.append("aab")\nif(b>a) res.append("bba")\nelse res.append("ab")\n\nyou might be thinking what if we will be using more numbers of a and b. there is a trick at the end we will be taking substring of this resultant string of size (a+b).\nnow go through the code you will get better insight.\n\nif you find it help full please upvote.\n\n```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n int size=a+b;\n string res="";\n while(a||b){\n if(a>b){\n res+="aab"; \n a-=2;\n b-=1;\n a=max(0,a);\n b=max(0,b);\n }\n else if(b>a){\n res+="bba"; \n a-=1;\n b-=2;\n a=max(0,a);\n b=max(0,b);\n } \n else{\n res+="ab";\n b-=1;\n a-=1;\n b=max(0,b);\n a=max(0,a);\n }\n }\n return res.substr(0,size);\n }\n};\n``` | 1 | 0 | [] | 1 |
string-without-aaa-or-bbb | Java solution for this one and 1405 | java-solution-for-this-one-and-1405-by-a-wkfb | \n\tclass Solution {\n public String strWithout3a3b(int a, int b) {\n return longestDiverseString(a, b, 0);\n }\n \n public String longestDiv | anduchencang | NORMAL | 2021-08-05T23:34:36.068727+00:00 | 2021-08-05T23:35:07.145912+00:00 | 89 | false | ```\n\tclass Solution {\n public String strWithout3a3b(int a, int b) {\n return longestDiverseString(a, b, 0);\n }\n \n public String longestDiverseString(int a, int b, int c) {\n PriorityQueue<Pair> pq = new PriorityQueue<>(\n (x, y) -> Integer.compare(y.freq, x.freq)\n );\n \n if(a != 0) {\n Pair pa = new Pair(\'a\', a);\n pq.offer(pa);\n }\n \n if(b != 0) {\n Pair pb = new Pair(\'b\', b);\n pq.offer(pb);\n }\n \n if(c != 0) {\n Pair pc = new Pair(\'c\', c);\n pq.offer(pc);\n }\n \n StringBuilder sb = new StringBuilder();\n \n while(!pq.isEmpty()) {\n if(pq.size() == 1) {\n int k = Math.min(pq.peek().freq, 2);\n for(int i = 0; i < k; i++) {\n sb.append(pq.peek().ch);\n } \n return sb.toString();\n }\n \n Pair p1 = pq.poll();\n Pair p2 = pq.poll();\n \n int k = Math.min(1 + p1.freq - p2.freq, 2);\n \n for(int i = 0; i < k; i++) {\n sb.append(p1.ch);\n }\n \n sb.append(p2.ch);\n \n p1.freq -= k;\n p2.freq -= 1;\n \n if(p1.freq > 0) pq.offer(p1);\n if(p2.freq > 0) pq.offer(p2);\n }\n \n return sb.toString();\n }\n \n private class Pair {\n char ch;\n int freq;\n \n Pair(char ch, int freq) {\n this.ch = ch;\n this.freq = freq;\n }\n }\n}\n``` | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | c++ recursion 100% | c-recursion-100-by-theeason123-atab | \nclass Solution {\npublic:\n string strWithout3a3b(int a, int b, string rtnstr = "") {\n \n int totalcount = a + b;\n int counta = 2;\n | Theeason123 | NORMAL | 2021-06-22T08:21:20.493201+00:00 | 2021-06-22T08:21:20.493277+00:00 | 50 | false | ```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b, string rtnstr = "") {\n \n int totalcount = a + b;\n int counta = 2;\n int countb = 2;\n \n if(totalcount == 0){\n return rtnstr;\n }\n \n if(rtnstr.size()>1){\n \n if(a < b and (std::strcmp(&rtnstr[rtnstr.size()-1], "b") == 0) and (std::strcmp(&rtnstr[rtnstr.size()-1], "b") == 0)){\n rtnstr += "a";\n a -= 1;\n counta -= 1;\n }\n \n if(b < a and std::strcmp(&rtnstr[rtnstr.size()-1], "a") == 0 and (std::strcmp(&rtnstr[rtnstr.size()-1], "a") == 0)){\n rtnstr += "b";\n b -= 1;\n countb -= 1;\n }\n \n \n }\n \n\n \n while(a >= b and a > 0 and counta > 0){\n rtnstr += "a";\n a -= 1;\n counta -= 1; \n } \n\n \n \n while(b>=a and b > 0 and countb > 0){\n rtnstr += "b";\n b -= 1;\n countb -= 1; \n }\n\n \n \n \n rtnstr = strWithout3a3b(a,b, rtnstr);\n \n return rtnstr;\n \n \n }\n};\n``` | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | java simple idea 100% | java-simple-idea-100-by-rohanraon-sslw | ```\nclass Solution {\n public String strWithout3a3b(int a, int b) {\n \n// (a,b)->(2,3) ababb (10,2) ababaaaa invalid test case (if(abs(a-b)>3) t | rohanraon | NORMAL | 2021-06-17T10:16:58.389216+00:00 | 2021-06-17T10:17:42.936151+00:00 | 80 | false | ```\nclass Solution {\n public String strWithout3a3b(int a, int b) {\n \n// (a,b)->(2,3) ababb (10,2) ababaaaa invalid test case (if(abs(a-b)>3) then invalid)\n// a>b aabaabaab\n// b>a bbabba..\n// a=b abababab\n \n StringBuilder sb=new StringBuilder("");\n// if it is a valid case when b==0 no of a\'s can\'t be 3 0r more\n if(b==0){\n while(a>0){sb.append("a");a--;}\n return sb.toString();\n }\n if(a==0){\n while(b>0){sb.append("b");b--;}\n return sb.toString();\n }\n// if a and b are same (3,3)->ababab\n// if a>b then aabaab but b might become 0 \n if(a==b){\n while(a!=0){\n sb.append("a");\n sb.append("b");\n a--;\n }\n return sb.toString();\n }else if(a>b){\n while(a>b&&b>0){\n sb.append("aa");\n sb.append("b");\n a-=2;\n b-=1;\n }\n sb.append(strWithout3a3b(a,b));\n return sb.toString();\n }\n \n while(b>a&&a>0){\n sb.append("bb");\n sb.append("a");\n b-=2;\n a-=1;\n }\n sb.append(strWithout3a3b(a,b));\n \n \n return sb.toString();\n }\n} | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | 0ms Java Solution | Greedy | 0ms-java-solution-greedy-by-raj02-rd68 | \nclass Solution {\n public String strWithout3a3b(int a, int b) {\n int a_count = 0;\n int b_count = 0;\n int n = a + b;\n \n | raj02 | NORMAL | 2021-06-16T07:04:53.539295+00:00 | 2021-06-16T07:04:53.539339+00:00 | 196 | false | ```\nclass Solution {\n public String strWithout3a3b(int a, int b) {\n int a_count = 0;\n int b_count = 0;\n int n = a + b;\n \n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < n; i++)\n {\n if(a >= b && a_count < 2 || b_count == 2 && a > 0 ){\n sb.append(\'a\');\n a--;\n a_count++;\n b_count = 0;\n }\n \n else if(b >=a && b_count < 2 || a_count == 2 && b > 0 ){\n sb.append(\'b\');\n b--;\n a_count = 0;\n b_count++;\n }\n \n }\n return sb.toString(); \n \n }\n}\n``` | 1 | 0 | ['Greedy', 'Java'] | 0 |
string-without-aaa-or-bbb | C++ | Priority Queue | 0ms | 100% | c-priority-queue-0ms-100-by-hg3994-liz9 | \nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n priority_queue<pair<int, char>> pq;\n if(a) pq.push({a,\'a\'});\n | hg3994 | NORMAL | 2021-06-15T10:51:04.173080+00:00 | 2021-06-15T10:51:04.173119+00:00 | 223 | false | ```\nclass Solution {\npublic:\n string strWithout3a3b(int a, int b) {\n priority_queue<pair<int, char>> pq;\n if(a) pq.push({a,\'a\'});\n if(b) pq.push({b,\'b\'});\n string ans = "";\n while(pq.size()>1){\n pair<int, char> one = pq.top(); pq.pop();\n pair<int, char> two = pq.top(); pq.pop();\n \n if(one.first >= 2){\n ans+= one.second;\n ans+= one.second;\n one.first -=2;\n }\n else{\n ans+= one.second;\n one.first -=1;\n }\n \n if(two.first >= 2 && two.first >= one.first){\n ans+= two.second;\n ans+= two.second;\n two.first -=2;\n }\n else{\n ans+= two.second;\n two.first -=1;\n }\n if(one.first > 0)\n pq.push(one);\n if(two.first > 0)\n pq.push(two);\n } \n if(pq.empty())\n return ans;\n if(pq.top().first >= 2){\n ans += pq.top().second;\n ans += pq.top().second;\n }\n else{\n ans += pq.top().second;\n }\n return ans;\n \n }\n};\n``` | 1 | 0 | ['C', 'Heap (Priority Queue)', 'C++'] | 0 |
string-without-aaa-or-bbb | Easy Python Solution | easy-python-solution-by-dhwanilshah2403-ofk7 | \n\t\tans = \'\'\n while a > 0 or b > 0:\n if a > b and a > 1 and b > 0:\n ans += \'aab\'\n a -= 2\n | dhwanilshah2403 | NORMAL | 2021-05-02T05:02:54.081572+00:00 | 2021-05-02T05:02:54.081601+00:00 | 66 | false | ```\n\t\tans = \'\'\n while a > 0 or b > 0:\n if a > b and a > 1 and b > 0:\n ans += \'aab\'\n a -= 2\n b -= 1\n if a < b and b > 1 and a > 0:\n ans += \'bba\'\n b -= 2\n a -= 1\n if a == b and a > 0 and b > 0:\n ans+=\'ab\'\n a -= 1\n b -= 1\n if a > 0 and b == 0:\n ans+=a*\'a\'\n a = 0\n if b > 0 and a == 0:\n ans+=b*\'b\'\n b = 0\n return ans\n\n``` | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | Java very simple greedy solution beats 100% | java-very-simple-greedy-solution-beats-1-wg7z | Simple idea is that if we have a >= 2*b or b >= 2*a then we consume greedily 2 chars from the character that has more characters followed by the other char. Con | techguy | NORMAL | 2021-04-05T18:18:21.412595+00:00 | 2021-04-05T18:18:21.412623+00:00 | 69 | false | Simple idea is that if we have `a >= 2*b` or `b >= 2*a` then we consume greedily 2 chars from the character that has more characters followed by the other char. Continue doing this repeatedely. Doing so we ensure that the last appended character is the char with lesser count. Now if we have `a >b` then append `ab`, else `ba`. \n\n```\nclass Solution {\n public String strWithout3a3b(int a, int b) {\n \n StringBuilder sb = new StringBuilder();\n while (a > 0 && b > 0) {\n if (a >= 2*b) {\n sb.append("aab");\n a -= 2;\n b -= 1;\n } else if (b >= 2*a) {\n sb.append("bba");\n b -= 2;\n a -= 1;\n } else if (a > b) {\n sb.append("ab");\n b -= 1;\n a -= 1;\n } else {\n sb.append("ba");\n b -= 1;\n a -= 1;\n }\n }\n \n for (int i = 0; i < a; i++) sb.append("a");\n for (int i = 0; i < b; i++) sb.append("b");\n return sb.toString();\n \n }\n}\n```\n``` | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | java Solution || 100% faster | java-solution-100-faster-by-abhishekjain-zryd | \nclass Solution {\n public String strWithout3a3b(int a, int b) {\n StringBuilder s= new StringBuilder();\n if(a==0 && b==0)\n {\n | abhishekjain581 | NORMAL | 2021-03-18T16:57:45.248829+00:00 | 2021-03-18T16:59:07.292440+00:00 | 230 | false | ```\nclass Solution {\n public String strWithout3a3b(int a, int b) {\n StringBuilder s= new StringBuilder();\n if(a==0 && b==0)\n {\n return "";\n }\n\n else{\n \n if(a>b)\n {\n while(a>0)\n {\n s.append("a");\n a--;\n \n if(a>b)\n {\n s.append("a");\n a--;\n \n }\n \n if(b>0)\n {\n s.append("b");\n b--;\n }\n }\n }\n else if(b>a)\n {\n while(b>0)\n {\n s.append("b");\n b--;\n \n if(b>a)\n {\n s.append("b");\n b--;\n \n }\n \n if(a>0)\n {\n s.append("a");\n a--;\n }\n }\n }\n else{\n while(a!=0 && b!=0)\n {\n s.append("ab");\n a--;\n b--;\n }\n }\n }\n \n return s.toString();\n \n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
string-without-aaa-or-bbb | Recursive C++ | Beats 100% | recursive-c-beats-100-by-tanyarajhans7-g0c9 | \nclass Solution {\npublic:\n string s="";\n string strWithout3a3b(int a, int b) {\n if(a==0)\n return string(b,\'b\');\n else if | tanyarajhans7 | NORMAL | 2021-02-03T19:12:38.070143+00:00 | 2021-02-03T19:12:38.070192+00:00 | 85 | false | ```\nclass Solution {\npublic:\n string s="";\n string strWithout3a3b(int a, int b) {\n if(a==0)\n return string(b,\'b\');\n else if(b==0)\n return string(a,\'a\');\n else if(a>b)\n return "aab"+strWithout3a3b(a-2, b-1);\n else if(b>a)\n return "bba"+strWithout3a3b(a-1, b-2);\n else if(a==b)\n return "ab"+strWithout3a3b(a-1, b-1);\n return "";\n }\n};\n``` | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | [Python3] greedy O(N) | python3-greedy-on-by-ye15-5iho | Algo\nHere, the strategy is that we choose b whenever we can. Now the question is when it is impossible to put b. There are 2 cases \n1) I just put 2 bs in plac | ye15 | NORMAL | 2020-12-24T04:01:03.451865+00:00 | 2020-12-24T04:01:03.451894+00:00 | 117 | false | **Algo**\nHere, the strategy is that we choose `b` whenever we can. Now the question is when it is impossible to put `b`. There are 2 cases \n1) I just put 2 `b`s in place;\n2) there ain\'t enough `b` left to guarentee no `aaa` (here, the condition to avoid this situation is `2*b < a`). \n\n**Implementation**\n```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n ans = []\n while a and b: \n if ans[-2:] == ["b"]*2 or 2*b < a: \n ans.append("a")\n a -= 1\n else: \n ans.append("b")\n b -= 1\n ans.extend(a*["a"] + b*["b"])\n return "".join(ans)\n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)`\n\nA few words for the 2nd condition. \nSuppose we put a `b` in the current place. Then, there are `b-1` `"b"`s left which are enough to host at most `b` chunks of `"aa"`. So if there are more `"a"` than `2*b`, then we have to put in an `"a"`. Otherwise, a `"aaa"` is guarenteed to occur. | 1 | 0 | ['Python3'] | 0 |
string-without-aaa-or-bbb | Python solution with simple calculations | python-solution-with-simple-calculations-vawr | \nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n res=[]\n d=a-b\n if d>0:\n g=min(d,b)\n res | umadevi_r | NORMAL | 2020-12-06T18:50:57.109072+00:00 | 2020-12-06T18:50:57.109119+00:00 | 86 | false | ```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n res=[]\n d=a-b\n if d>0:\n g=min(d,b)\n res=["aab"]*g\n a-=2*g\n b-=g\n elif d<0:\n g=min(-d,a)\n res=["bba"]*g\n b-=2*g\n a-=g\n p=min(a,b)\n res+=["ab"]*p\n a-=p;b-=p\n res+=["a"]*a+["b"]*b\n return "".join(res)\n``` | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | Easy [C++] Greedy Solution 0ms | easy-c-greedy-solution-0ms-by-jintaejin-zc1p | \nclass Solution {\npublic:\n string strWithout3a3b(int A, int B) {\n string ans = "";\n while(A>0 or B>0)\n {\n int n = ans. | jinTaeJin | NORMAL | 2020-11-26T07:55:43.807388+00:00 | 2020-11-26T07:57:24.986539+00:00 | 102 | false | ```\nclass Solution {\npublic:\n string strWithout3a3b(int A, int B) {\n string ans = "";\n while(A>0 or B>0)\n {\n int n = ans.size();\n if(n>1 and ans[n-1]==\'a\' and ans[n-2]==\'a\')\n ans+=\'b\', B--;\n\n else if(n>1 and ans[n-1]==\'b\' and ans[n-2]==\'b\')\n ans+=\'a\', A--;\n \n else\n {\n if(A>B) \n ans+=\'a\', A--;\n else \n ans+=\'b\', B--;\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | Python 99% Faster | python-99-faster-by-wpriddy50-nd8u | class Solution:\n def strWithout3a3b(self, A: int, B: int) -> str:\n a = list(A * \'a\')\n b = list(B * \'b\')\n ans = []\n while | wpriddy50 | NORMAL | 2020-09-08T06:01:47.092007+00:00 | 2020-09-08T06:01:47.092071+00:00 | 91 | false | class Solution:\n def strWithout3a3b(self, A: int, B: int) -> str:\n a = list(A * \'a\')\n b = list(B * \'b\')\n ans = []\n while True:\n try: \n ans.append(a.pop())\n ans.append(b.pop())\n except:\n break\n return ans + a + b | 1 | 0 | [] | 2 |
string-without-aaa-or-bbb | Java Solution 100% Runtime 73% Space | java-solution-100-runtime-73-space-by-di-nzmg | \nclass Solution {\n public String strWithout3a3b(int A, int B) {\n StringBuilder w = new StringBuilder();\n while(A >0 && B >0){\n if(A | dimitriderose | NORMAL | 2020-08-21T04:04:41.091681+00:00 | 2020-08-21T04:04:41.091724+00:00 | 91 | false | ```\nclass Solution {\n public String strWithout3a3b(int A, int B) {\n StringBuilder w = new StringBuilder();\n while(A >0 && B >0){\n if(A==B){\n w.append("a");\n w.append("b");\n A --;\n B --;\n continue;\n }\n if(Math.abs(A-B) > 0){\n if(A> B){\n A -=2;\n B--;\n w.append(\'a\');\n w.append(\'a\');\n w.append(\'b\');\n\n \n }else{\n B -= 2;\n A--;\n w.append(\'b\');\n w.append(\'b\');\n w.append(\'a\');\n\n } \n }else{\n \n A--;\n B--;\n w.append(\'a\');\n w.append(\'b\');\n }\n }\n \n while (A > 0){\n A--;\n w.append(\'a\');\n }\n while(B > 0){\n B--;\n w.append(\'b\');\n }\n return w.toString();\n }\n}\n``` | 1 | 0 | [] | 1 |
string-without-aaa-or-bbb | Clean Python | One-Liner + O(1) Space Complexity | clean-python-one-liner-o1-space-complexi-0veo | Clean Python | One-Liner + O(1) Space Complexity\n\nThe Python code works based on the following algorithm:\n\n1. If A==B, we output "ab" repeated "A" times. (T | aragorn_ | NORMAL | 2020-08-11T05:38:23.230587+00:00 | 2020-08-11T17:55:32.655066+00:00 | 180 | false | **Clean Python | One-Liner + O(1) Space Complexity**\n\nThe Python code works based on the following algorithm:\n\n1. If A==B, we output "ab" repeated "A" times. (Trivial Answer).\n\n2. If A and B are different, we define the variables "H=max(a,b)" (highest) and "L=min(A,B)" (lowest). For each variable, we store the associated characters in the variables "x" and "y". Note: (x,y)=(a,b) when A>B and (x,y)=(b,a) otherwise.\n\n3. We now divide our solution space into L+1 "bin containers", which represent the highest number of divisions we can achieve with our minimum number "L". In these bins, we will store the characters of our "high" variable "H".\n\n4. Initially, our bins are filled with one "x" letter. However, some bins must receive 2 letters to store all "H" characters. We satisfy this condition by placing two "x" characters in the first "H-(L+1)" bins.\n\n5. We join our "bin" containers using "y" characters. Since "L+1" containers have "L" spaces in-between, we effectively use "H+L=A+B" characters, and thus have a valid answer :)\n\nI hope the explanation was helpful. The algorithm is really easy after making a small diagram. Cheers,\n\n**A) Standard Version**\n```\nclass Solution:\n def strWithout3a3b(self, A, B):\n if A==B:\n return "ab"*A\n #\n if A>B:\n H,L = A,B\n x,y = "ab"\n else: # B<A\n H,L = B,A\n x,y = "ba"\n #\n bins = L+1\n doubles = H - bins\n x2 = x*2\n res = [x2] * doubles + [x] * (bins-doubles)\n return y.join( res )\n```\n\n**B) O(1) Space Solver**\n\n```\nclass Solution:\n def solver(self,A,B):\n # Internal Solver Function\n # Works with O(1) Space Complexity\n if A==B:\n for _ in range(A):\n yield "ab"\n return\n #\n if A>B:\n H,L = A,B\n x,y = "ab"\n else: # B<A\n H,L = B,A\n x,y = "ba"\n #\n bins = L+1\n doubles = H - bins\n x2 = x*2\n for i in range(bins):\n yield x2 if i<doubles else x\n if i<L:\n yield y\n def strWithout3a3b(self, A, B):\n return \'\'.join( self.solver(A,B) )\n```\n\n**C) One-Liner (Explicit Loop)**\n\nThis solution condenses all the previous logic into a single expression. It has a time and space complexity of O(A+B), despite the presence of many redundant checks.\n\n```\nclass Solution:\n def strWithout3a3b(self, A, B):\n return "ab"*A if A==B else ("a" if A<B else "b").join( [ ("a" if A>B else "b")*( 2 if i<(max(A,B)-min(A,B)-1) else 1) for i in range(min(A,B)+1) ])\n```\n\n**D) One-Liner (Array Sum)**\n\nThis new one-liner solution builds two separate arrays containing single and duplicates entries, and merges them through the sum operator. It\'s only a reconversion :)\n\nPS. I also made the replacement "abs(A-B) = max(A,B)-min(A,B)"\n```\nclass Solution:\n def strWithout3a3b(self, A, B):\n return "ab"*A if A==B else ("a" if A<B else "b").join( \\\n ["aa" if A>B else "bb"]*(abs(A-B)-1) + \\\n ["a" if A>B else "b" ]*( min(A,B) - abs(A-B) + 2 ) )\n``` | 1 | 1 | ['Python', 'Python3'] | 0 |
string-without-aaa-or-bbb | very simple C++ code | very-simple-c-code-by-luoyuf-l14r | \nstring strWithout3a3b(int A, int B) {\n\tstring s, res = "";\n\tif (A >= B) s = "ab";\n\telse s = "ba";\n\twhile (A || B) {\n\t\tif (A > B) res += "a", --A;\n | luoyuf | NORMAL | 2020-07-22T04:46:12.619398+00:00 | 2020-07-22T04:46:12.619433+00:00 | 88 | false | ```\nstring strWithout3a3b(int A, int B) {\n\tstring s, res = "";\n\tif (A >= B) s = "ab";\n\telse s = "ba";\n\twhile (A || B) {\n\t\tif (A > B) res += "a", --A;\n\t\telse if (B > A) res += "b", --B;\n\t\tif (A && B) res += s, --A, --B;\n\t}\n\treturn res;\n}\n``` | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | [C++] Simple Solution(100% Time, 98% Memory) | c-simple-solution100-time-98-memory-by-a-msyf | \n\nclass Solution {\npublic:\n \n string strWithout3a3b(int A, int B) {\n \n string finalStr = "";\n while(A || B)\n\t\t{ // Check w | avinsit123 | NORMAL | 2020-07-04T10:24:28.131721+00:00 | 2020-07-04T10:24:28.131764+00:00 | 68 | false | \n```\nclass Solution {\npublic:\n \n string strWithout3a3b(int A, int B) {\n \n string finalStr = "";\n while(A || B)\n\t\t{ // Check whether either A or B is zero \n if(!A) {finalStr += ((B==1) ? "b" : "bb"); break;}\n if(!B) {finalStr += ((A==1) ? "a" : "aa"); break;}\n \n if(A>B) {\n finalStr += "aab";\n A-=2; B-=1; }\n else if(A==B) {\n finalStr += "ab";\n A--; B--;}\n else {\n finalStr += "bba";\n A-=1; B-=2; }\n \n }\n return finalStr;\n }\n};\n``` | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | Python String Equations | python-string-equations-by-rushabhh24-3i60 | ```\nstrWithout3a3b(self, A: int, B: int) -> str:\n if A > B:\n if B/A > 0.5:\n return \'aab\' * (A - B) + \'ab\' * (B - (A - B | rushabhh24 | NORMAL | 2020-05-27T16:21:56.170306+00:00 | 2020-05-27T16:26:48.003580+00:00 | 79 | false | ```\nstrWithout3a3b(self, A: int, B: int) -> str:\n if A > B:\n if B/A > 0.5:\n return \'aab\' * (A - B) + \'ab\' * (B - (A - B))\n else:\n return \'aab\' * B + \'a\' * (A - 2 * B)\n else:\n if A/B > 0.5:\n return \'bba\' * (B - A) + \'ba\' * (A - (B - A))\n else:\n return \'bba\' * A + \'b\' * (B - 2 * A) | 1 | 0 | [] | 0 |
string-without-aaa-or-bbb | Python Code [Intuitive] | python-code-intuitive-by-adi10hero-yzc5 | \nclass Solution:\n def solve(self,a,b, A, B):\n # a is the character with count A (may or maynot be \'a\')\n\t\t\t# b is the character with coun | adi10hero | NORMAL | 2020-05-26T08:11:18.455100+00:00 | 2020-05-26T08:11:18.455133+00:00 | 160 | false | ```\nclass Solution:\n def solve(self,a,b, A, B):\n # a is the character with count A (may or maynot be \'a\')\n\t\t\t# b is the character with count B (may or maynot be \'b\')\n\t\t\t# Note : A >= B (check how we\'re calling the function)\n\t\t\tans = []\n idx = 2\n numB = B\n while A and B:\n if A >= 2*B:\n ans.append(a)\n A-=1\n if A:\n ans.append(a)\n A-=1\n ans.append(b)\n B-=1\n else:\n ans.append(a)\n A-=1\n if A:\n ans.append(a)\n A-=1\n ans.append(b)\n B-=1\n if B:\n ans.append(b)\n B-=1\n while A:\n ans.append(a)\n A-=1\n while B:\n ans.append(b)\n B-=1\n return ans\n def strWithout3a3b(self, A: int, B: int) -> str:\n \n ans = []\n if A < 3 and B < 3:\n return \'a\'*A + \'b\'*B\n if B < A:\n return \'\'.join(self.solve(\'a\',\'b\', A, B))\n else:\n return \'\'.join(self.solve(\'b\',\'a\',B, A))\n```\n\nSimple and Intuitive.\nPlease reply if any further explanation is needed. | 1 | 0 | ['Greedy', 'Python3'] | 0 |
maximum-erasure-value | An Interesting Optimisation | JAVA Explanation | an-interesting-optimisation-java-explana-vsln | Introduction:\nBefore we discuss the optimisation, let\'s make sure we\'re on the same page regarding the classic two-pointer approach.\nWe can solve this quest | ciote | NORMAL | 2022-06-12T01:13:25.937980+00:00 | 2022-06-12T09:13:43.882248+00:00 | 6,794 | false | ### Introduction:\nBefore we discuss the optimisation, let\'s make sure we\'re on the same page regarding the classic two-pointer approach.\nWe can solve this question by simply expanding a right pointer while keeping track of the sum until we reach a value we\'ve seen before. Then, we increment our left pointer until the duplicate no longer exists. Finally, we can just update our maximum sum! I\'ve included the code for this approach below as well.\n\n### Optimising our code:\nNow, as you may have noticed, we continuously expand our left pointer until we reach that duplicate. Doesn\'t it feel like we could be saving some time here? I mean, if we already knew the <ins>last indexes of all values</ins>, we could just jump our left pointer straight there. Awesome, now we\'re getting somewhere.\n\n> Interview tip: To optimise your code, look for inefficiencies or repetitive work in your current approach and see if you can negate them. \n\nHang on, but what about our sums? The benefit of the regular two-pointer approach was that we get to adjust our sum while our left pointer is increasing. Well, what if we already knew the sums at any given range? Turns out we can do this using a prefix sum array.\n\n> Interview tip: If you find yourself thinking "man, it would be great if I had x", then try to enforce that behaviour in your algorithm.\n\n### Prefix Sums:\nThe idea behind prefix sums is that if we want the sum between the range `[left, right]`, we can obtain it by evaluating: \n**`sum[left, right] = sum[0, right] - sum[0, left - 1]`**. In other words, this is a *range sum query*.\n\nObserve this in the below illustration:\n\n\nIn other words, the sum from any range from 0 to `i` where `i` is any index in the array, is called the <ins>prefix sum</ins>. If we store the prefix sum at each index, we can obtain any given sum range! If we combine this idea with the idea to keep track of "last indexes", we have ourselves an optimised approach.\n\nAnd there we have it! Just by spending a bit more extra space, we managed to improve our linear solution quite a bit! Now we\'re ready to start coding.\n___\n### Code:\n**Two-pointer Solution:**\n> Time complexity: `O(n)`\n> Space complexity: `O(m)` where `m` is the number of unique elements.\n```java\npublic int maximumUniqueSubarray(int[] nums) { \n\tint maxScore = 0, currScore = 0;\n\tSet<Integer> set = new HashSet<>();\n\n\tfor (int l=0, r=0; r<nums.length; r++) {\n\t\twhile (!set.add(nums[r])) {\n\t\t\tcurrScore -= nums[l];\n\t\t\tset.remove(nums[l++]);\n\t\t}\n\t\tcurrScore += nums[r];\n\t\tmaxScore = Math.max(maxScore, currScore);\n\t}\n\n\treturn maxScore;\n}\n```\n**Prefix Sum Solution:**\n> Time complexity: `O(n)`\n> Space complexity: `O(n)`\n```java\npublic int maximumUniqueSubarray(int[] nums) {\n\tMap<Integer, Integer> lastIndex = new HashMap<>();\n\tint[] prefixSum = new int[nums.length + 1];\n\n\tint maxScore = 0;\n\tfor (int l=0, r=0; r<nums.length; r++) {\n\t\tprefixSum[r+1] = prefixSum[r] + nums[r];\n\t\tif (lastIndex.containsKey(nums[r])) \n\t\t\tl = Math.max(l, lastIndex.get(nums[r]) + 1);\n\t\tmaxScore = Math.max(maxScore, prefixSum[r+1] - prefixSum[l]);\n\t\tlastIndex.put(nums[r], r);\n\t}\n\n\treturn maxScore;\n}\n```\nNote: Both approaches can be improved using arrays instead of a set or map! I left the sets and maps in there to make the intention clear for this guide. | 112 | 0 | ['Two Pointers', 'Prefix Sum', 'Java'] | 9 |
maximum-erasure-value | Java O(n) - Sliding Window + HashSet | java-on-sliding-window-hashset-by-dev_ps-w5pq | \nclass Solution {\n public int maximumUniqueSubarray(int[] nums) {\n \n Set<Integer> set = new HashSet();\n \n int sum =0, ans =0 | dev_ps | NORMAL | 2020-12-20T04:10:10.433207+00:00 | 2020-12-20T04:13:29.388810+00:00 | 11,371 | false | ```\nclass Solution {\n public int maximumUniqueSubarray(int[] nums) {\n \n Set<Integer> set = new HashSet();\n \n int sum =0, ans =0;\n int j = 0;\n \n int i = 0;\n \n while(i<nums.length && j<nums.length){\n \n if(!set.contains(nums[j])){\n \n sum+=nums[j];\n ans = Math.max(sum,ans);\n set.add(nums[j++]);\n }else{\n \n sum = sum-nums[i];\n set.remove(nums[i++]);\n }\n }\n\n return ans;\n }\n}\n``` | 97 | 3 | ['Two Pointers'] | 21 |
maximum-erasure-value | [Python] sliding window solution, explained | python-sliding-window-solution-explained-15gx | In this problem we need to find subarray with biggest sum, which has only unique elements. This is in fact almost the same as problem 3. Longest Substring Witho | dbabichev | NORMAL | 2021-05-28T09:50:42.470538+00:00 | 2021-05-28T12:19:15.168234+00:00 | 4,909 | false | In this problem we need to find subarray with biggest sum, which has only unique elements. This is in fact almost the same as problem **3. Longest Substring Without Repeating Characters**, but here we need to find sum, not length. But idea is exaclty the same:\n\nLet us keep window with elements `[beg: end)`, where first element is included and last one is not. For example `[0, 0)` is empty window, and `[2, 4)` is window with `2` elements: `2`-th and `3`-th.\n\nLet us discuss our algorithm now:\n\n1. `S` is set of symbols in our window, we use set to check in `O(1)` if new symbol inside it or not.\n2. `beg = end = 0` in the beginning, so we start with empty window, also `ans = 0` and `n = len(nums)` and `sm = 0`: sum of elements in window.\n3. Now, we continue, until one of two of our pointers reaches the end. First, we try to extend our window to the right: check `s[end]` in window and if we can, add it to set, move end pointer to the right and update `sm` and `ans`. If we can not add new symbol to set, it means it is already in window set, and we need to move `beg` pointer to the right, update `sm` and remove elements from `S`.\n\n#### Complexity\nWe move both of our pointers only to the right, so time complexity is `O(n)`. Space complexity is potentially `O(n)` as well.\n\n#### Code\n```python\nclass Solution:\n def maximumUniqueSubarray(self, nums):\n beg, end, S, n, sm = 0, 0, set(), len(nums), 0\n ans = 0\n while end < n:\n if nums[end] not in S:\n sm += nums[end]\n S.add(nums[end])\n end += 1\n ans = max(ans, sm)\n else:\n sm -= nums[beg]\n S.remove(nums[beg])\n beg += 1\n \n return ans \n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 92 | 13 | ['Two Pointers', 'Sliding Window'] | 6 |
maximum-erasure-value | [Python/Java/C++] Sliding Window & HashMap - Clean & Concise - O(N) | pythonjavac-sliding-window-hashmap-clean-xxxw | Idea\n- This problem is about to find the maximum sum of subarrray (where elements in subarray is unique) in an array.\n- This is a classic Sliding Window probl | hiepit | NORMAL | 2021-05-28T07:16:11.897494+00:00 | 2021-05-28T09:22:05.168985+00:00 | 3,737 | false | **Idea**\n- This problem is about to find the **maximum sum** of subarrray (where elements in subarray is unique) in an array.\n- This is a classic Sliding Window problem which is simillar to this problem [3. Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)\n- We use `seen` (HashMap) to keep track of last index of a number.\n- We use `sum` to keep sum of sub array in range `[l..r]` so far where elements are unique.\n- While extend right side `r` if we met an existed number then we move left side `l` until `seen[nums[r]] + 1` and of course, we need to decrease `sum` corresponding.\n\n**Complexity**\n- Time: `O(N)`, where `N` is number of elements in array `nums`.\n- Space: `O(M)`, where `M <= N` is the maximum number of distinct numbers in an subarray.\n\n**Python 3**\n```python\nclass Solution:\n def maximumUniqueSubarray(self, nums: List[int]) -> int:\n seen = dict()\n ans = sum = 0\n l = 0\n for r, x in enumerate(nums):\n if x in seen:\n index = seen[x]\n while l <= index: # Move the left side until index + 1\n del seen[nums[l]]\n sum -= nums[l]\n l += 1\n\n seen[x] = r\n sum += x\n ans = max(ans, sum)\n return ans\n```\n\n**Java**\n```java\nclass Solution {\n public int maximumUniqueSubarray(int[] nums) {\n Map<Integer, Integer> seen = new HashMap<>();\n int l = 0, sum = 0, ans = 0;\n for (int r = 0; r < nums.length; r++) {\n int x = nums[r];\n if (seen.containsKey(x)) {\n int index = seen.get(x);\n while (l <= index) { // Move the left side until index + 1\n seen.remove(nums[l]);\n sum -= nums[l];\n l += 1;\n }\n }\n seen.put(x, r);\n sum += x;\n ans = Math.max(ans, sum);\n }\n return ans;\n }\n}\n```\n\n**C++**\n```c++\nclass Solution {\npublic:\n int maximumUniqueSubarray(vector<int>& nums) {\n unordered_map<int, int> seen;\n int l = 0, sum = 0, ans = 0;\n for (int r = 0; r < nums.size(); r++) {\n int x = nums[r];\n if (seen.find(x) != seen.end()) {\n int index = seen[x];\n while (l <= index) { // Move the left side until index + 1\n seen.erase(nums[l]);\n sum -= nums[l];\n l += 1;\n }\n }\n seen[x] = r;\n sum += x;\n ans = max(ans, sum);\n }\n return ans;\n }\n};\n```\n | 70 | 29 | [] | 5 |
maximum-erasure-value | ✅ [C++/Python] Simple Solution w/ Explanation | Sliding Window | cpython-simple-solution-w-explanation-sl-vytm | If you are doing Daily LeetCoding Challenge for June, I highly recommend you look at the problem given on June 10: 3. Longest Substring Without Repeating Charac | r0gue_shinobi | NORMAL | 2022-06-12T02:34:51.785194+00:00 | 2022-06-12T03:56:24.547193+00:00 | 6,955 | false | If you are doing Daily LeetCoding Challenge for June, I highly recommend you look at the problem given on June 10: [3. Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/). I have already briefly discussed that problem [in this post](https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2132954).\nBut if you are visiting this problem for the first time, I still recommend you to see that problem and try to find a similarity with this one \uD83D\uDE42. Here, we need to maximize the subarray sum instead of the length.\n___\n___\n\u274C **Solution I: Brute-Force [TLE]**\n\nStarting with each index, we can check all subarrays till we find a repeating number. We can use a set to store the numbers we\'ve encountered so far to check for repetition.\n\n```python\nclass Solution:\n def maximumUniqueSubarray(self, nums: List[int]) -> int:\n max_sum = 0\n seen = set()\n for l in range(len(nums)):\n seen.clear()\n curr_sum = 0\n r = l\n while r < len(nums):\n if nums[r] in seen:\n break\n curr_sum += nums[r]\n seen.add(nums[r])\n r += 1\n max_sum = max(max_sum, curr_sum)\n return max_sum\n```\n\n- **Time Complexity:** `O(n\xB2)`\n- **Space Complexity:** `O(1)`\n___\n\u2705 **Solution II (a): Sliding Window + Set [Accepted]**\n\nIf you haven\'t heard the term "sliding window" before, visit [this link](https://stackoverflow.com/questions/8269916/what-is-sliding-window-algorithm-examples).\n\nThe sliding windows approach is a two-pointer approach. Still, I refrained from saying it because I\'m not actually using 2 pointers. The left bound of the window is defined by `l` and the right bound by the index of `num`.\n\n**Algorithm:**\n\n1. Create a sliding window: `[nums[l], nums[l + 1], ..., num].`\n2. For each number in the `nums` array, we check if this `num` is already present in the window. We can use a set to lookup in `O(1)`.\n3. If the number is present in the window, we keep shrinking the window from the left until there\'s no repetition.\n4. We update the set by adding `num` and repeat the above process.\n\n**Example:**\n```text\nnums = [4,2,1,2,6]\n1. Window: [4]; set = {4}; curr_sum = 4; max_sum = 4\n2. Window: [4, 2]; set = {4, 2}; curr_sum = 6; max_sum = 6\n3. Window: [4, 2, 1]; set = {4, 2, 1}; curr_sum = 7; max_sum = 7\n4(a). Window: [2, 1, 2]; set = {2, 1}; curr_sum = 5; max_sum = 7\n4(b). Window: [1, 2]; set = {1, 2}; curr_sum = 3; max_sum = 7\n5. Window: [1, 2, 6]; set = {1, 2, 6}; curr_sum = 9; max_sum = 9\n```\n\n<iframe src="https://leetcode.com/playground/bUc7dtpg/shared" frameBorder="0" width="1080" height="360"></iframe>\n\n- **Time Complexity:** `O(n)`\n- **Space Complexity:** `O(k)`, where k is the number of distinct elements. Here, `k = 10\u2074` (See constraints)\n___\n\u2705 **Solution II (b): Sliding Window + Array [Accepted]**\n\nWe create a sliding window whose left bound is defined by `l` and the right bound by `r`. We try to expand this window towards the right so that no number inside is repeated. In the previous approach to know whether `nums[r]` is already inside this window or not, we used a set. But in this case, we are using an array to know by storing the previous index of each element.\nHow storing the previous index will help?\n\u27A1\uFE0F If the previous index of `nums[r]`, i.e., `prev[nums[r]] >= l`, it means previous `nums[r]` is towards the right of `l`. In other words, inside the current window.\n\n<iframe src="https://leetcode.com/playground/aspW6KyX/shared" frameBorder="0" width="1080" height="350"></iframe>\n\n- **Time Complexity:** `O(n)`\n- **Space Complexity:** `O(k)`, where k is the number of distinct elements. Here, `k = 10\u2074` (See constraints)\n\n___\n**FAQs:**\n\n1. Why the time complexity for the second approach is `O(n)` instead of `O(n\xB2)`?\n\u27A1\uFE0F Don\'t get confused by looking at the nested loops. Focus on how many elements both the pointers are traversing through. For `r`, it is `n` elements. For `l`, it is `n` in the worst case. So, `O(n) + O(n)` which is effectively `O(n)`.\n___\n___\nIf you like the solution, please **upvote**! \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n | 66 | 0 | ['Two Pointers', 'Sliding Window', 'Ordered Set', 'Python'] | 7 |
maximum-erasure-value | C++ O(n) sliding window with hash set | c-on-sliding-window-with-hash-set-by-min-xpbp | \nclass Solution {\npublic:\n int maximumUniqueSubarray(vector<int>& nums) {\n int result = 0;\n unordered_set<int> hset;\n for (int i = | mingrui | NORMAL | 2020-12-20T04:03:46.115904+00:00 | 2020-12-20T04:03:46.115950+00:00 | 9,191 | false | ```\nclass Solution {\npublic:\n int maximumUniqueSubarray(vector<int>& nums) {\n int result = 0;\n unordered_set<int> hset;\n for (int i = 0, j = 0, win = 0; j < nums.size(); j++) {\n while (hset.find(nums[j]) != hset.end()) {\n hset.erase(nums[i]);\n win -= nums[i];\n i++;\n }\n hset.insert(nums[j]);\n win += nums[j];\n result = max(result, win);\n }\n return result;\n }\n};\n``` | 63 | 0 | [] | 10 |
maximum-erasure-value | ✅ Maximum Erasure Value | Easy Solution using 2-Pointers and Hashset w/ Explanation | maximum-erasure-value-easy-solution-usin-vfhh | \u2714\uFE0F Solution (using 2-Pointers and HashSet)\n\nWe need to check every sub-array having unique elements and find the one having the maximum sum. Obvious | archit91 | NORMAL | 2021-05-28T08:01:04.017938+00:00 | 2021-05-28T08:54:36.866701+00:00 | 3,555 | false | \u2714\uFE0F ***Solution (using 2-Pointers and HashSet)***\n\nWe need to check every sub-array having unique elements and find the one having the maximum sum. Obviously, with the given constraints, we can\'t check every sub-array individually.\n\nWe need to realise that we can **choose the first element and keep extending the array till we find a duplicate**. We can insert all the chosen elements till now into a hashset and check if the element already exists before inserting the next one. We will simultaneously also keep track of the sum of all chosen elements - *`cursum`* and maintain the max sum till now - *`ans`*\n\nWhen our next element ***`nums[r]`* is already present in currently chosen subarray** (hashset), then we must **delete all the elements from the start till the duplicate**. For this, we will need to maintain a left-pointer *`l`* denoting the left-most index of an element in currently chosen subarray. \n\nWe will keep deleting *`nums[l]`* and simultaneously deducting it from *`cur_sum`* and incrementing *`l`* pointer till duplicate is deleted. Finally we add *`nums[r]`* to our hashset and `cur_sum`. We repeat till we reach the end.\n\n**C++**\n```\nint maximumUniqueSubarray(vector<int>& nums) { \n\tint n = size(nums), cur_sum = 0, ans = 0, l = 0, r = 0;\n\tunordered_set<int> s;\n\twhile(r < n) {\n\t\twhile(s.find(nums[r]) != end(s)) // delete from current sub-array till there\'s a duplicate of nums[r]\n\t\t\tcur_sum -= nums[l], s.erase(nums[l++]);\n\t\tcur_sum += nums[r], s.insert(nums[r++]); // pick nums[r] and update cur_sum\n\t\tans = max(ans, cur_sum); // finally update ans to hold the maximum of all subarray sums till now\n\t}\n\treturn ans;\n}\n```\n\n---\n\n**Python**\n```\ndef maximumUniqueSubarray(self, nums: List[int]) -> int:\n\tsub_arr, l, cur_sum, ans = set(), 0, 0, 0\n\tfor r in range(len(nums)):\n\t\twhile nums[r] in sub_arr: # deleting duplciate of nums[r], if already exists \n\t\t\tsub_arr.remove(nums[l])\n\t\t\tcur_sum -= nums[l]\n\t\t\tl += 1\n\t\tsub_arr.add(nums[r]) # pick nums[r]\n\t\tcur_sum += nums[r] # update current sub-array sum\n\t\tans = max(ans, cur_sum) # update ans to hold max of all sub-array sums till now\n\treturn ans\n```\n\n***Time Complexity :*** **`O(N)`**, where *`N`* is the number of elements in *`nums`*\n***Space Complexity :*** **`O(N)`**\n\n---\n\n\u2714\uFE0F ***Solution - II (using 2-Pointers and Frequency array)***\n\nIt\'s given that all the element in `nums` are in the range `[1, 10000]`. We can use a frequency-array with indices `[1,10000]` to denote if an element is already chosen. \n\nThis method gave significant improvement in the runtime speed & memory of C++ (from ~360ms to <100ms). The improvement was negligible in case of python\n\n**C++**\n```\nint maximumUniqueSubarray(vector<int>& nums) { \n\tint n = size(nums), cur_sum = 0, ans = 0, l = 0, r = 0;\n bool freq[10001]{false};\n\twhile(r < n) {\n\t\twhile(freq[nums[r]])\n\t\t\tcur_sum -= nums[l], freq[nums[l++]] = false;\n\t\tcur_sum += nums[r], freq[nums[r++]] = true; \n\t\tans = max(ans, cur_sum); \n\t}\n\treturn ans;\n}\n```\n\n---\n\n**Python**\n```\ndef maximumUniqueSubarray(self, nums: List[int]) -> int:\n\tfreq, l, cur_sum, ans = [False]*10001, 0, 0, 0\n\tfor r in range(len(nums)):\n\t\twhile freq[nums[r]]:\n\t\t\tfreq[nums[l]] = False\n\t\t\tcur_sum -= nums[l]\n\t\t\tl += 1\n\t\tfreq[nums[r]] = True\n\t\tcur_sum += nums[r]\n\t\tans = max(ans, cur_sum)\n\treturn ans\n```\n\n***Time Complexity :*** **`O(N)`**, where *`N`* is the number of elements in *`nums`*\n***Space Complexity :*** **`O(1)`**, although we are using array of size 10000, it doesn\'t depend on the size of input and hence the extra space used is constant - `O(1)`\n\n---\n\n*Best Runtime -*\n\n<table><tr><td><img src =https://assets.leetcode.com/users/images/e7193d6c-9e7e-4da3-a891-abb85294f4c7_1622191896.538263.png /></td></tr></table>\n\n\n\n\n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, please do comment below \uD83D\uDC47 \n\n---\n--- | 51 | 2 | ['C', 'Python'] | 2 |
maximum-erasure-value | ✅ Easy Solution using 2 Pointers with HashSet w/ Explanation | Beats 100% | easy-solution-using-2-pointers-with-hash-9dj8 | \u2714\uFE0F Solution (using 2-Pointers and HashSet)\n\nWe need to check every sub-array having unique elements and find the one having the maximum sum. Obvious | archit91 | NORMAL | 2021-05-28T07:58:37.597232+00:00 | 2021-05-28T08:56:23.013247+00:00 | 1,840 | false | \u2714\uFE0F ***Solution (using 2-Pointers and HashSet)***\n\nWe need to check every sub-array having unique elements and find the one having the maximum sum. Obviously, with the given constraints, we can\'t check every sub-array individually.\n\nWe need to realise that we can **choose the first element and keep extending the array till we find a duplicate**. We can insert all the chosen elements till now into a hashset and check if the element already exists before inserting the next one. We will simultaneously also keep track of the sum of all chosen elements - *`cursum`* and maintain the max sum till now - *`ans`*\n\nWhen our next element ***`nums[r]`* is already present in currently chosen subarray** (hashset), then we must **delete all the elements from the start till the duplicate**. For this, we will need to maintain a left-pointer *`l`* denoting the left-most index of an element in currently chosen subarray. \n\nWe will keep deleting *`nums[l]`* and simultaneously deducting it from *`cur_sum`* and incrementing *`l`* pointer till duplicate is deleted. Finally we add *`nums[r]`* to our hashset and `cur_sum`. We repeat till we reach the end.\n\n**C++**\n```\nint maximumUniqueSubarray(vector<int>& nums) { \n\tint n = size(nums), cur_sum = 0, ans = 0, l = 0, r = 0;\n\tunordered_set<int> s;\n\twhile(r < n) {\n\t\twhile(s.find(nums[r]) != end(s)) // delete from current sub-array till there\'s a duplicate of nums[r]\n\t\t\tcur_sum -= nums[l], s.erase(nums[l++]);\n\t\tcur_sum += nums[r], s.insert(nums[r++]); // pick nums[r] and update cur_sum\n\t\tans = max(ans, cur_sum); // finally update ans to hold the maximum of all subarray sums till now\n\t}\n\treturn ans;\n}\n```\n\n---\n\n**Python**\n```\ndef maximumUniqueSubarray(self, nums: List[int]) -> int:\n\tsub_arr, l, cur_sum, ans = set(), 0, 0, 0\n\tfor r in range(len(nums)):\n\t\twhile nums[r] in sub_arr: # deleting duplciate of nums[r], if already exists \n\t\t\tsub_arr.remove(nums[l])\n\t\t\tcur_sum -= nums[l]\n\t\t\tl += 1\n\t\tsub_arr.add(nums[r]) # pick nums[r]\n\t\tcur_sum += nums[r] # update current sub-array sum\n\t\tans = max(ans, cur_sum) # update ans to hold max of all sub-array sums till now\n\treturn ans\n```\n\n***Time Complexity :*** **`O(N)`**, where *`N`* is the number of elements in *`nums`*\n***Space Complexity :*** **`O(N)`**\n\n---\n\n\u2714\uFE0F ***Solution - II (using 2-Pointers and Frequency array)***\n\nIt\'s given that all the element in `nums` are in the range `[1, 10000]`. We can use a frequency-array with indices `[1,10000]` to denote if an element is already chosen. \n\nThis method gave significant improvement in the runtime speed & memory of C++ (from ~360ms to <100ms). The improvement was negligible in case of python\n\n**C++**\n```\nint maximumUniqueSubarray(vector<int>& nums) { \n\tint n = size(nums), cur_sum = 0, ans = 0, l = 0, r = 0;\n bool freq[10001]{false};\n\twhile(r < n) {\n\t\twhile(freq[nums[r]])\n\t\t\tcur_sum -= nums[l], freq[nums[l++]] = false;\n\t\tcur_sum += nums[r], freq[nums[r++]] = true; \n\t\tans = max(ans, cur_sum); \n\t}\n\treturn ans;\n}\n```\n\n---\n\n**Python**\n```\ndef maximumUniqueSubarray(self, nums: List[int]) -> int:\n\tfreq, l, cur_sum, ans = [False]*10001, 0, 0, 0\n\tfor r in range(len(nums)):\n\t\twhile freq[nums[r]]:\n\t\t\tfreq[nums[l]] = False\n\t\t\tcur_sum -= nums[l]\n\t\t\tl += 1\n\t\tfreq[nums[r]] = True\n\t\tcur_sum += nums[r]\n\t\tans = max(ans, cur_sum)\n\treturn ans\n```\n\n***Time Complexity :*** **`O(N)`**, where *`N`* is the number of elements in *`nums`*\n***Space Complexity :*** **`O(1)`**, although we are using array of size 10000, it doesn\'t depend on the size of input and hence the extra space used is constant - `O(1)`\n\n---\n\n*Best Runtime -*\n\n<table><tr><td><img src =https://assets.leetcode.com/users/images/e7193d6c-9e7e-4da3-a891-abb85294f4c7_1622191896.538263.png /></td></tr></table>\n\n\n\n\n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, please do comment below \uD83D\uDC47 \n\n---\n--- | 26 | 6 | ['C', 'Python'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.