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
remove-colored-pieces-if-both-neighbors-are-the-same-color
🗓️ Daily LeetCoding Challenge October, Day 2
daily-leetcoding-challenge-october-day-2-ar5p
This problem is the Daily LeetCoding Challenge for October, Day 2. Feel free to share anything related to this problem here! You can ask questions, discuss what
leetcode
OFFICIAL
2023-10-02T00:00:05.698280+00:00
2023-10-02T00:00:05.698330+00:00
2,952
false
This problem is the Daily LeetCoding Challenge for October, Day 2. Feel free to share anything related to this problem here! You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made! --- If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide - **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem. - **Images** that help explain the algorithm. - **Language and Code** you used to pass the problem. - **Time and Space complexity analysis**. --- **📌 Do you want to learn the problem thoroughly?** Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis. <details> <summary> Spoiler Alert! We'll explain this 1 approach in the official solution</summary> **Approach 1:** Count </details> If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)! --- <br> <p align="center"> <a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank"> <img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" /> </a> </p> <br>
5
0
[]
36
remove-colored-pieces-if-both-neighbors-are-the-same-color
Javascript Solution
javascript-solution-by-sunitmody-dkry
The trick here is to figure out how many total moves Alice and Bob will get in this game. If Alice has more moves than Bob then Alice wins. Otherwise Bob wins.\
sunitmody
NORMAL
2022-10-11T19:30:42.851205+00:00
2022-10-11T19:30:42.851241+00:00
271
false
The trick here is to figure out how many total moves Alice and Bob will get in this game. If Alice has more moves than Bob then Alice wins. Otherwise Bob wins.\n\ne.g. \'AAAABBBBAAA\'\n\n* We have four A\'s in a row in the beginning.\n\t* This means that Alice can do two moves here.\n* Then we have four B\'s in a row.\n\t* This means that Bob can do two moves here.\n* FInally we have three A\'s in a row.\n\t* This means that Alice can do one move here.\n\nThe total we get is 4 moves for Alice and 2 moves for Bob. So Alice wins.\n\nFor each consequitive group of same letter that are 3 or more in a row, the number of moves will be that count minus 2. So if 4 in a row, then that person can do 2 moves.\n\n``` \nvar winnerOfGame = function(colors) {\n\t// COUNT HOW MANY MOVES ALICE GETS\n let aliceMoves = 0;\n let aCount = 0;\n \n for (let i = 0; i < colors.length; i ++) {\n\t\t// IF WE HAVE THE CORRECT COLOR THEN WE INCREMENT THE COUNT\n if (colors[i] === \'A\') {\n aCount ++;\n }\n \n\t\t// IF THE COLOR CHANGES TO THE WRONG COLOR OR IF WE REACHED THE END OF THE STRING THEN WE CHECK IF 3 OR MORE TO GET THE MOVE COUNT\n if (colors[i] === \'B\' || i === colors.length - 1) {\n if (aCount >= 3) {\n aliceMoves += (aCount - 2);\n }\n aCount = 0;\n }\n }\n \n\t// COUNT HOW MANY MOVES BOB GETS\n let bobMoves = 0;\n let bCount = 0;\n \n for (let i = 0; i < colors.length; i ++) {\n if (colors[i] === \'B\') {\n bCount ++;\n }\n \n if (colors[i] === \'A\' || i === colors.length - 1) {\n if (bCount >= 3) {\n bobMoves += (bCount - 2);\n }\n bCount = 0;\n }\n }\n \n return aliceMoves > bobMoves;\n};\n\ntime O(n)\nspace O(1)
5
0
['JavaScript']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
[Python]: Count AAA and BBB and "return AAA > BBB"
python-count-aaa-and-bbb-and-return-aaa-9pivt
The basic idea here is that we count how many three consecutive AAA and BBB since Alice is only allowed to remove \'A\' if its neigbors are \'A\', i.e., AAA. Th
abuomar2
NORMAL
2021-10-17T16:49:11.756385+00:00
2021-10-17T16:49:11.756410+00:00
559
false
The basic idea here is that we count how many three consecutive AAA and BBB since Alice is only allowed to remove \'A\' if its neigbors are \'A\', i.e., A**A**A. Thus, we count how many \'AAA\' and \'BBB\' and whoever has more will defintely win since the other one will run out of characters to remove earlier/faster. \n\n``` \ndef winnerOfGame(self, colors: str) -> bool:\n \n count_AAA = count_BBB = 0\n \n for i in range(1, len(colors) - 1):\n if colors[i-1] == colors[i] == colors[i+1] == \'A\':\n count_AAA += 1\n \n if colors[i-1] == colors[i] == colors[i+1] == \'B\':\n count_BBB += 1\n \n \n return count_AAA > count_BBB\n\n```
5
0
['Python', 'Python3']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
[JAVA] 100% fast, with explanation in detail
java-100-fast-with-explanation-in-detail-m7vi
\'\'\'\nclass Solution {\n public boolean winnerOfGame(String colors) {\n \n if(colors.length() <=2)\n {\n return false; //
Shourya112001
NORMAL
2021-10-16T18:05:58.903597+00:00
2021-10-16T18:05:58.903633+00:00
564
false
\'\'\'\nclass Solution {\n public boolean winnerOfGame(String colors) {\n \n if(colors.length() <=2)\n {\n return false; // BOB will win if "AA" or "BB" or "A" or "B"\n }\n \n int[] triple = triplets(colors); //Calculating all the triplets in the string AAA, BBB\n\n if(triple[0] > triple[1])\n {\n return true; //Alice wins, as it has more number of triplets\n }\n else\n {\n return false; //Bob wins, also this condition will be true when triple A == triple B \n }\n }\n\n \n public int[] triplets(String colors)\n {\n int tripleA = 0, tripleB = 0;\n \n for(int i = 2; i<colors.length(); i++) // i=2, so that it does not give array out of bounds exception\n {\n //If, we get 3 continous A\'s\n if(colors.charAt(i-2) == \'A\' && colors.charAt(i-1) == \'A\' && colors.charAt(i) == \'A\')\n {\n tripleA++; \n }\n //If, we get 3 continous B\'s\n else if(colors.charAt(i-2) == \'B\' && colors.charAt(i-1) == \'B\' && colors.charAt(i) == \'B\')\n {\n tripleB++;\n }\n }\n return new int[] {tripleA, tripleB}; \n }\n}\n\'\'\'
5
1
['Java']
2
remove-colored-pieces-if-both-neighbors-are-the-same-color
O(N) python
on-python-by-saurabht462-fa4d
```\ndef winnerOfGame(self, colors: str) -> bool:\n alice=0\n bob =0\n for i in range(1,len(colors)-1):\n if colors[i]=="A":\n
saurabht462
NORMAL
2021-10-16T16:00:39.012654+00:00
2021-10-16T16:01:27.945025+00:00
399
false
```\ndef winnerOfGame(self, colors: str) -> bool:\n alice=0\n bob =0\n for i in range(1,len(colors)-1):\n if colors[i]=="A":\n if colors[i-1]=="A" and colors[i+1]=="A":\n alice+=1\n else:\n if colors[i-1]=="B" and colors[i+1]=="B":\n bob+=1\n return alice>bob
5
2
[]
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Simple C++ solution using only counts. Detailed Explanation
simple-c-solution-using-only-counts-deta-uy0k
Intuition\n Describe your first thoughts on how to solve this problem. \nHello y\'all. So this problem states that there are 2 people Alice and Bob who are play
chandu_345
NORMAL
2023-10-02T08:47:15.896783+00:00
2023-10-02T16:57:04.352643+00:00
215
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHello y\'all. So this problem states that there are 2 people $$Alice$$ and $$Bob$$ who are playing a 2 - player turn based game. The idea of the game is to remove a color (represented by $$\'A\'$$ or $$\'B\'$$) from a string of colors . As we know there are basic ground rules for every game and this game has some ground rules as well.\n\n---\n\n- Alice is only allowed to remove a piece colored $$\'A\'$$ if both its neighbors are also colored $$\'A\'$$. She is not allowed to remove pieces that are colored $$\'B\'$$.\n- Bob is only allowed to remove a piece colored $$\'B\'$$ if both its neighbors are also colored $$\'B\'$$. He is not allowed to remove pieces that are colored $$\'A\'$$.\n- Alice and Bob cannot remove pieces from the edge of the line.\n- If a player cannot make a move on their turn, that player loses and the other player wins. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nLet\'s try to understand the logic before we jump into the code. So from the rules we can say that the only way for $$Alice$$ to make a move is that there have to be 3 consecutive $$\'A\'$$ in the string $$colors$$. \n- This means that if in colors there is a substring $$AAA$$ and the $$A$$ in between can be removed to make it $$AA$$ in one turn played by $$Alice$$.\n\nSimilarly the only way for $$Bob$$ to make a move is if there exists 3 consecutive $$\'B\'$$ in $$colors$$.\n\n- This means that if in colors there is a substring $$BBB$$ and the $$B$$ in between can be removed to make it $$BB$$ in one turn played by $$Bob$$.\n\nWe might think that there might be possible cases where one player\'s move might cause a disruption for the other player\'s move but that is not possible here since even after a player\'s turn there are still remaining characters which will not allow for clashes or disruptions to the other player.\n\nSo the simplest logic to this would be to count the number of 3 consecutive $$A$$\'s and $$B$$\'s and see which is greater. If the count is equal then $$Bob$$ wins because he played the last turn and $$Alice$$ does not have a chance to play in the next round.\n\n# Complexity\n- Time complexity:$$O(n)$$ since we are iterating only once to find out the 3 consecutive occurrences of the individual colors ($$A$$ and $$B$$) .\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \n- Space complexity:$$O(1)$$ since we require only 2 variables to store the count of 3 consective $$A$$\'s and the count of 3 consective $$B$$\'s .\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int n=colors.size(),counta=0,countb=0; //Declare variables\n for(int i=1;i<n-1;i++)\n {\n if(colors[i-1]==\'A\' && colors[i]==\'A\' && colors[i+1]==\'A\')//Check if there are 3 consecutive A\'s\n {\n counta+=1; // If yes add to count\n }\n if(colors[i-1]==\'B\' && colors[i]==\'B\' && colors[i+1]==\'B\')//Check if there are 3 consecutive B\'s\n {\n countb+=1; //If yes add to count\n }\n }\n return counta>countb; //Compare which count is more and return true or false based on that\n }\n};\n```\n**IF THIS SOLUTION HELPED YOU PLEASE CONSIDER UPVOTING TYSM :))**
4
0
['C++']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
NOOB CODE : Easy to Understand
noob-code-easy-to-understand-by-harshava-k18z
Approach\n\n1. It initializes two variables al and bo to 0 to keep track of the number of consecutive colors for player \'A\' and player \'B\', respectively.\n\
HARSHAVARDHAN_15
NORMAL
2023-10-02T07:19:45.393147+00:00
2023-10-02T07:19:45.393181+00:00
118
false
# Approach\n\n1. It initializes two variables `al` and `bo` to 0 to keep track of the number of consecutive colors for player \'A\' and player \'B\', respectively.\n\n2. It then iterates through the string `colors` from the second character (index 1) to the second-to-last character (index `len(colors) - 2`).\n\n3. Inside the loop, it checks if the current character is \'A\' and if it\'s the same as the previous and next characters. If all these conditions are met, it increments the `al` counter. Similarly, it checks for \'B\' and increments the `bo` counter.\n\n4. Finally, it compares the `al` and `bo` counters and returns `True` if `al` is greater than `bo`, indicating that player \'A\' is the winner, or `False` otherwise.\n\n# Complexity\n- Time complexity: ***O(n)***\n\n- Space complexity: ***O(1)***\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n al=0\n bo=0\n for i in range(1,len(colors)-1):\n if (colors[i]==\'A\' and colors[i]==colors[i-1] and colors[i]==colors[i+1]):\n al+=1\n elif (colors[i]==\'B\' and colors[i]==colors[i-1] and colors[i]==colors[i+1]):\n bo+=1\n if(al>bo):\n return(True)\n else:\n return(False)\n```
4
0
['Python3']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Video Solution | Explanation With Drawings | In Depth | C++ | Java | Python 3
video-solution-explanation-with-drawings-87b4
Intuition and approach discussed in detail in video solution\nhttps://youtu.be/Pkywd65nA6Q\n\n# Code\nC++\n\nclass Solution {\npublic:\n bool winnerOfGame(st
Fly_ing__Rhi_no
NORMAL
2023-10-02T02:02:13.498505+00:00
2023-10-02T02:02:13.498523+00:00
139
false
# Intuition and approach discussed in detail in video solution\nhttps://youtu.be/Pkywd65nA6Q\n\n# Code\nC++\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int threeA = 0;\n int threeB = 0;\n int sz = colors.size();\n for(int indx = 1; indx < sz - 1; indx++){\n if(colors[indx] == \'A\' && colors[indx+1] == \'A\' && colors[indx-1] == \'A\'){\n\n threeA++;\n }else if(colors[indx] == \'B\' && colors[indx+1] == \'B\' && colors[indx-1] == \'B\'){\n threeB++;\n }\n }\n return threeA > threeB;\n }\n};\n```\nJava\n```\nclass Solution {\n public boolean winnerOfGame(String clrs) {\n int threeA = 0;\n int threeB = 0;\n int sz = clrs.length();\n char colors[] = clrs.toCharArray();\n for(int indx = 1; indx < sz - 1; indx++){\n if(colors[indx] == \'A\' && colors[indx+1] == \'A\' && colors[indx-1] == \'A\'){\n\n threeA++;\n }else if(colors[indx] == \'B\' && colors[indx+1] == \'B\' && colors[indx-1] == \'B\'){\n threeB++;\n }\n }\n return threeA > threeB;\n }\n}\n```\nPython 3\n```\nclass Solution:\n def winnerOfGame(self, clrs: str) -> bool:\n threeA = 0\n threeB = 0\n sz = len(clrs)\n colors = list(clrs)\n for indx in range(1, sz - 1):\n if colors[indx] == \'A\' and colors[indx+1] == \'A\' and colors[indx-1] == \'A\':\n threeA += 1\n elif colors[indx] == \'B\' and colors[indx+1] == \'B\' and colors[indx-1] == \'B\':\n threeB += 1\n return threeA > threeB\n```
4
0
['C++', 'Java', 'Python3']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Maintain 1 score Greedy
maintain-1-score-greedy-by-glamour-1wim
Intuition\nWe do not need to maintain two scores. Only one alice_over_bob is enough.\n\n\n# Approach\n Describe your approach to solving the problem. \n\n# Comp
glamour
NORMAL
2023-10-02T01:46:21.820208+00:00
2023-10-02T01:46:21.820229+00:00
31
false
# Intuition\nWe do not need to maintain two scores. Only one `alice_over_bob` is enough.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n fun winnerOfGame(colors: String): Boolean {\n var alice_over_bob = 0\n for(i in 1 until colors.length - 1)\n if (colors[i - 1] == colors[i] && colors[i + 1] == colors[i])\n alice_over_bob += if(colors[i] == \'A\') 1 else -1\n return alice_over_bob > 0\n }\n}\n```
4
0
['Kotlin']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
🔥💥 Easy Simple C++ Code With O(n) Time Complexity & O(1) Space Complexity 💥🔥
easy-simple-c-code-with-on-time-complexi-q5jd
Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to determine the winner of a game based on a sequence of colors denoted by
eknath_mali_002
NORMAL
2023-10-02T00:41:20.028165+00:00
2023-10-02T00:41:20.028183+00:00
240
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to determine the winner of a game based on a sequence of colors denoted by \'A\' and \'B\'. We aim to count the occurrences of \'A\' and \'B\' sequences of length 3 or more. The player with the most such occurrences is declared the winner.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize counters for player \'A\' (`cnt_a`) and player \'B\' (`cnt_b`) to keep track of valid sequences for each player.\n2. Traverse the input colors string character by character.\n3. For each character:\n - If it\'s `\'A\'`, count the length of the \'A\' sequence and update cnt_a accordingly if the `length is 3 or more`. \n - If it\'s `\'B\'`, count the length of the \'B\' sequence and update cnt_b accordingly if the `length is 3 or more`.\n4. Compare the counts (`cnt_a` and `cnt_b`) to determine the winner of the game.\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 bool winnerOfGame(string colors) {\n int cnt_a = 0;\n int cnt_b = 0;\n int n=colors.size();\n int j(0);\n while(j<n){\n if(colors[j]==\'A\'){\n int cnt =0;\n while(colors[j]==\'A\' and j<n){\n cnt++;\n j++;\n }\n if(cnt>=3) cnt_a += cnt-2;\n }\n if(colors[j]==\'B\'){\n int cnt =0;\n while(colors[j]==\'B\' and j<n){\n cnt++;\n j++;\n }\n if(cnt>=3) cnt_b += cnt-2;\n }\n }\n\n return cnt_a > cnt_b;\n }\n};\n```
4
0
['String', 'Greedy', 'Game Theory', 'C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Java | String | Counting | Simple Solution
java-string-counting-simple-solution-by-y925w
\nclass Solution {\n public boolean winnerOfGame(String colors) {\n int as=0,bs=0; \n for (int i=1;i<colors.length()-1;i++) {\n
Divyansh__26
NORMAL
2022-09-16T08:03:51.236672+00:00
2022-09-16T08:03:51.236710+00:00
815
false
```\nclass Solution {\n public boolean winnerOfGame(String colors) {\n int as=0,bs=0; \n for (int i=1;i<colors.length()-1;i++) {\n if(colors.charAt(i-1)==\'A\' && colors.charAt(i)==\'A\' && colors.charAt(i+1)==\'A\') \n as++;\n if(colors.charAt(i-1)==\'B\' && colors.charAt(i)==\'B\' && colors.charAt(i+1)==\'B\') \n bs++;\n }\n return as>bs;\n }\n}\n```\nKindly upvote if you like the code.
4
0
['String', 'Counting', 'Java']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
Python simple solution
python-simple-solution-by-mukeshr-8jtb
Just scan the array and count the number of consecutive A\'s or B\'s of length 3\n\n\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n
mukeshR
NORMAL
2022-08-02T02:30:25.480448+00:00
2022-08-02T02:30:25.480477+00:00
332
false
Just scan the array and count the number of consecutive A\'s or B\'s of length 3\n\n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n \n num_3consecutive_As = 0\n num_3consecutive_Bs = 0\n \n for i in range(0, len(colors)-2):\n \n if colors[i] == colors[i+1] == colors[i+2]:\n if colors[i] == \'A\':\n num_3consecutive_As += 1\n else:\n num_3consecutive_Bs += 1\n \n return num_3consecutive_As > num_3consecutive_Bs\n```
4
0
[]
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Sliding window | Single Pass | O(1) space
sliding-window-single-pass-o1-space-by-s-u0ro
\n# Approach\nUsing sliding window of size if size>2 then add size-2 in the index of Alice/freqa[0] or Bob/freqb[1] else add 0 our window is not useful\n\n\n# C
seal541
NORMAL
2024-01-08T03:27:42.022794+00:00
2024-01-08T03:27:42.022823+00:00
6
false
\n# Approach\nUsing sliding window of `size` if size>2 then add `size-2` in the index of `Alice`/`freqa[0]` or `Bob`/`freqb[1]` else add `0` our window is not useful\n\n\n# Complexity\n- Time complexity:\n`O(n)`\n\n- Space complexity:\n`O(1)`\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n // try - sliding window\n int left = 0;\n int right = 0;\n vector<int> freqa(2,0);\n\n\n while(right<colors.size()){\n int size = 0;\n while(colors[right]==colors[left]){\n size+=1;\n right+=1;\n }\n\n freqa[colors[left]-\'A\']+=size>2?size-2:0;\n left=right;\n }\n return freqa[0]>freqa[1];\n }\n};\n```
3
0
['String', 'Sliding Window', 'C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
1 Liner Easy | Java | Explained✅
1-liner-easy-java-explained-by-4ryangaut-3uab
colors.replaceAll("A{3,}", "AA"): This part of the code uses the replaceAll method to search for substrings of "A" that appear three or more times consecutively
4ryangautam
NORMAL
2023-10-02T07:01:43.814967+00:00
2023-10-02T07:09:17.901115+00:00
145
false
- colors.replaceAll("A{3,}", "AA"): This part of the code uses the replaceAll method to search for substrings of "A" that appear three or more times consecutively and replace them with "AA". In regular expressions, "{3,}" means "three or more occurrences." So, this part of the code is essentially replacing sequences of three or more consecutive "A" characters with "AA" in the string referred to as colors.\n\n- colors.replaceAll("B{3,}", "BB"): Similarly, this part of the code uses replaceAll to search for substrings of "B" that appear three or more times consecutively and replace them with "BB".\n\n- colors.replaceAll("A{3,}", "AA").length(): This part of the code calculates the length of the string after performing the "A" replacement. It counts how many characters are in the modified string after replacing "AAA" with "AA" for each occurrence.\n\n- colors.replaceAll("B{3,}", "BB").length(): This part of the code calculates the length of the string after performing the "B" replacement. It counts how many characters are in the modified string after replacing "BBB" with "BB" for each occurrence.\n\n---\n\n\n- Finally, the code compares the lengths of the two modified strings and checks if the length of the string after replacing "AAA" with "AA" is less than the length of the string after replacing "BBB" with "BB". If this comparison is true, it means that there were more occurrences of "A" sequences replaced with "AA" than "B" sequences replaced with "BB," and the expression returns true. Otherwise, it returns false.\n\n# Code\n```\nclass Solution {\n public boolean winnerOfGame(String colors) {\n return colors.replaceAll("A{3,}", "AA").length() < colors.replaceAll("B{3,}", "BB").length();\n }\n}\n```
3
0
['Game Theory', 'Java']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Medium problem made easy! JavaScript solution (Slow though)
medium-problem-made-easy-javascript-solu-6yxd
Intuition\nThe problem seems to involve counting the number of consecutive sequences of the same color ("A" or "B") and determining the winner based on these co
shaakilkabir
NORMAL
2023-10-02T07:00:06.786339+00:00
2023-10-02T07:00:06.786370+00:00
198
false
# Intuition\nThe problem seems to involve counting the number of consecutive sequences of the same color ("A" or "B") and determining the winner based on these counts.\n\n# Approach\nWe can traverse the input string, keeping track of consecutive occurrences of each color ("A" or "B"). We\'ll count the number of each instance of three consecutive "A"s and "B"s. Finally, we\'ll compare these counts and determine the winner based on the larger count.\n\n# Complexity\n- Time complexity:\nO(n), where n is the length of the input string.\n\n- Space complexity:\nO(1), as we are using a constant amount of extra space regardless of the input size.\n\n# Code\n```\n/**\n * @param {string} colors\n * @return {boolean}\n */\nvar winnerOfGame = function(colors) {\n let alice = 0; // Counter for three consecutive "A"s\n let bob = 0; // Counter for three consecutive "B"s\n \n // Traverse the string and count consecutive occurrences of "A" and "B"\n for (let i = 0; i < colors.length; i++) {\n const element = colors[i];\n const prevEl = colors[i - 1];\n const nextEl = colors[i + 1];\n \n if (element === "A" && prevEl === "A" && nextEl === "A") {\n alice++;\n }\n if (element === "B" && prevEl === "B" && nextEl === "B") {\n bob++;\n }\n }\n \n return alice > bob;\n};\n```
3
0
['JavaScript']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
C++ Solution || Beats 99% || Easy To Understand
c-solution-beats-99-easy-to-understand-b-unwy
Easy To Understand Solution\n\n# Approach: Count\n\n# Intuition\nThere are two very important things to notice about this game that will allow us to easily sol
BruteForce_03
NORMAL
2023-10-02T06:25:34.499702+00:00
2023-10-02T06:31:45.993045+00:00
50
false
# Easy To Understand Solution\n\n# Approach: Count\n\n# Intuition\nThere are two very important things to notice about this game that will allow us to easily solve the problem:\n\nWhen one player removes a letter, it will never create a new removal opportunity for the other player. For example, let\'s say you had *"ABAA"*. If the *"B"* wasn\'t there, then Alice would have a new removal opportunity. However, the *"B"* can never be removed because of the rules of the game. This observation implies that at the start of the game, all moves are already available to both players.\nThe order in which the removals happen is irrelevant. This is a side effect of the previous observation. Let\'s say there was a section in the middle of the string *"BAAAAAB"*. Alice has three removal choices here, *"BA[A]AAAB"*, *"BAA[A]AAB"*, and *"BAAA[A]AB"*. However, her choice is irrelevant, because all three choices will result in *"BAAAAB"*.\n\n![POD-2.png](https://assets.leetcode.com/users/images/1c109c7c-ba73-4484-b167-ed4f5def41a3_1696228296.0426672.png)\n\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 bool winnerOfGame(string colors) {\n int alice=0;\n int bob=0;\n for(int i=1;i<colors.size()-1;i++)\n {\n if(colors[i-1]==\'A\' && colors[i+1]==\'A\' && colors[i]==\'A\')\n {\n alice++;\n }\n else if(colors[i-1]==\'B\' && colors[i+1]==\'B\' && colors[i]==\'B\')\n {\n bob++;\n }\n }\n cout<<alice<<" "<<bob<<endl;\n return alice>bob;\n }\n};\n```\n\n![upvote.jpg](https://assets.leetcode.com/users/images/bff6cb17-e6a2-463b-8ce0-e2e018e06d2f_1696227770.901257.jpeg)\n
3
0
['Greedy', 'Game Theory', 'C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
c++, Time:O(N), space:O(1) beginner friendly solution
c-timeon-spaceo1-beginner-friendly-solut-2nep
Intuition\nconsider an examples "AA" or "BB" or "A" or "B".From all this example we can understand string length should be greater than or equal to 3.Because wh
satya_siva_prasad
NORMAL
2023-10-02T05:41:50.939244+00:00
2023-10-02T05:41:50.939263+00:00
84
false
# Intuition\nconsider an examples "AA" or "BB" or "A" or "B".From all this example we can understand string length should be greater than or equal to 3.Because when string length is lessthan 3 we cann\'t find 3 consecutive A\'s. \nThis problems is as simple as finding number of 3 consecutive A\'s and \nnumber of 3 consecutive B\'s in given string.\nIf number of A\'s are greater than B\'s return True else return false.\n\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int n =colors.size();\n if(n<3)return false;//if size lessthan 3 we cann\'t find 3consecutive A\'s.\n int a=0;\n int b=0;\n for(int i=1;i<n-1;i++){\n if(colors[i-1]==\'A\' && colors[i]==\'A\' && colors[i+1]==\'A\')a++;//finding number of consecutive A\'s in string.\n if(colors[i-1]==\'B\' && colors[i]==\'B\' && colors[i+1]==\'B\')b++;//finding number of consecutive B\'s in string.\n }\n if(a-b>0)return true; // if number of A\'s is greather than B\'s return true.\n return false;\n }\n// if you understand this explaination please upvote.\n};\n```
3
0
['String', 'C++']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
Sliding Windows approach | Easy CPP
sliding-windows-approach-easy-cpp-by-him-hhj9
Upvote is you like the approach \n# Code\n\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int n=colors.size();\n if(n<=2) re
himanshumude01
NORMAL
2023-10-02T05:24:43.890310+00:00
2023-10-02T05:24:43.890343+00:00
85
false
## Upvote is you like the approach \n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int n=colors.size();\n if(n<=2) return false;\n int i=0,j=2;\n int cA=0,cB=0;\n while(j<n)\n {\n if(colors[i]==\'A\' and colors[i+1]==\'A\' and colors[j]==\'A\')\n {\n cA++;\n }\n else if(colors[i]==\'B\' and colors[i+1]==\'B\' and colors[j]==\'B\')\n {\n cB++;\n }\n i++;\n j++;\n\n }\n if(cA>cB) return true;\n else return false;\n\n }\n};\n```\n\n\n![image.png](https://assets.leetcode.com/users/images/06ea6a55-2aeb-495d-b1e5-74c4b14f52e3_1696224257.1960711.png)\n
3
0
['C++']
2
remove-colored-pieces-if-both-neighbors-are-the-same-color
✅ JavaScript - 94%, one pass, O(n)
javascript-94-one-pass-on-by-daria_abdul-b62c
Approach\n Describe your approach to solving the problem. \nWe can count the result of the game before the start because any turn of one player can\'t add new p
daria_abdulnasyrova
NORMAL
2023-04-01T08:02:25.676948+00:00
2023-04-01T08:07:06.287152+00:00
103
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can count the result of the game before the start because any turn of one player can\'t add new possible turns to another player. We count amount of possible turns for A and B in one pass, then compare it.\n\nTime complexity: $$O(n)$$.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} colors\n * @return {boolean}\n */\nvar winnerOfGame = function(colors) {\n let countA = 0;\n let countB = 0;\n\n for (let i = 1; i < colors.length - 1; i++) {\n countA += colors[i - 1] === \'A\' &&\n colors[i] === \'A\' &&\n colors[i + 1] === \'A\';\n \n countB += colors[i - 1] === \'B\' &&\n colors[i] === \'B\' &&\n colors[i + 1] === \'B\';\n }\n\n return countA > countB;\n};\n```
3
0
['JavaScript']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Java Solution using Sliding Window
java-solution-using-sliding-window-by-so-mvv9
\nclass Solution {\n public boolean winnerOfGame(String colors) {\n int countA = 0;\n int countB = 0;\n \n for (int i = 0; i < co
solved
NORMAL
2022-03-26T16:32:09.544445+00:00
2022-03-26T16:32:09.544480+00:00
328
false
```\nclass Solution {\n public boolean winnerOfGame(String colors) {\n int countA = 0;\n int countB = 0;\n \n for (int i = 0; i < colors.length() - 2; i++) {\n char c1 = colors.charAt(i);\n char c2 = colors.charAt(i + 1);\n char c3 = colors.charAt(i + 2);\n \n if (c1 == c2 && c2 == c3 && c1 == \'A\') {\n countA++;\n }\n \n if (c1 == c2 && c2 == c3 && c1 == \'B\') {\n countB++;\n }\n }\n \n return countA > countB;\n }\n}\n```
3
0
['Sliding Window', 'Java']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
C++ easiest solution!
c-easiest-solution-by-anchal_soni-vdjt
\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n \n int n=colors.size();\n if(n<=2) return false;\n\t\t\n int a
anchal_soni
NORMAL
2021-10-20T14:12:15.642662+00:00
2021-10-20T14:12:15.642706+00:00
369
false
```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n \n int n=colors.size();\n if(n<=2) return false;\n\t\t\n int a=0;\n int b=0;\n \n for(int i=1;i<n-1;++i)\n {\n if(colors[i]==\'A\' and colors[i-1]==\'A\' and colors[i+1]==\'A\') a++;\n if(colors[i]==\'B\' and colors[i-1]==\'B\' and colors[i+1]==\'B\') b++;\n }\n return a>b;\n \n }\n};\n```
3
0
['C', 'C++']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
JavaScript - JS
javascript-js-by-mlienhart-zk0p
\n/**\n * @param {string} colors\n * @return {boolean}\n */\nvar winnerOfGame = function (colors) {\n let a = 0;\n let b = 0;\n\n for (let i = 1; i < colors.
mlienhart
NORMAL
2021-10-18T21:21:57.560884+00:00
2021-10-18T21:21:57.560925+00:00
222
false
```\n/**\n * @param {string} colors\n * @return {boolean}\n */\nvar winnerOfGame = function (colors) {\n let a = 0;\n let b = 0;\n\n for (let i = 1; i < colors.length - 1; i++) {\n if (colors[i - 1] === colors[i] && colors[i + 1] === colors[i]) {\n colors[i] === "A" ? a++ : b++;\n }\n }\n\n return a > b;\n};\n```
3
0
[]
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
C++ Solution
c-solution-by-sanchitjain-gjop
\nclass Solution {\npublic:\n bool winnerOfGame(string c) {\n int a = 0,b =0;\n for(int i = 1 ; i < c.length()-1 ; i++){\n\t\t// Counting the n
sanchitjain
NORMAL
2021-10-16T16:19:38.317831+00:00
2021-10-25T11:19:22.122988+00:00
143
false
```\nclass Solution {\npublic:\n bool winnerOfGame(string c) {\n int a = 0,b =0;\n for(int i = 1 ; i < c.length()-1 ; i++){\n\t\t// Counting the number of \'AAA\' & \'BBB\'\n if( c[i] == \'A\' && c[i-1] == \'A\' && c[i+1] == \'A\' ){\n a++;\n }else if(c[i] == \'B\' && c[i-1] == \'B\' && c[i+1] == \'B\' ){\n b++;\n }\n }\n if(a>b){\n return true;\n }\n return false;\n }\n};\n```
3
0
['C']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
O(n) Time | Count consecutive AAAs & BBBs
on-time-count-consecutive-aaas-bbbs-by-i-u1cq
\nC++\n\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int cntA=0,cntB=0;\n for(int i=1;i<colors.size()-1;i++){\n\t\t\t// Co
inomag
NORMAL
2021-10-16T16:19:01.279596+00:00
2021-10-16T16:23:38.939769+00:00
267
false
\n***C++***\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int cntA=0,cntB=0;\n for(int i=1;i<colors.size()-1;i++){\n\t\t\t// Count of Consecutive \'AAA\'s which Alice can remove\n if(colors[i]==\'A\'&&colors[i-1]==\'A\'&&colors[i+1]==\'A\')cntA++;\n\t\t\t\n\t\t\t// Count of Consecutive \'BBB\'s which Bob can remove\n if(colors[i]==\'B\'&&colors[i-1]==\'B\'&&colors[i+1]==\'B\')cntB++;\n }\n\t\t\n\t\t// Alice wins if she can remove more \'AAA\'s than Bob can remove \'BBB\'s\n return cntA>cntB;\n }\n};\n```\n\n***Java***\n```\nclass Solution {\n public boolean winnerOfGame(String colors) {\n int cntA=0,cntB=0;\n for(int i=1;i<colors.length()-1;i++){\n if(colors.charAt(i)==\'A\'&&colors.charAt(i-1)==\'A\'&&colors.charAt(i+1)==\'A\')cntA++;\t\t\t\n if(colors.charAt(i)==\'B\'&&colors.charAt(i-1)==\'B\'&&colors.charAt(i+1)==\'B\')cntB++;\n }\n \n return cntA>cntB;\n }\n}\n```
3
0
['C', 'Java']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
understandable
understandable-by-user7868kf-o64j
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
user7868kf
NORMAL
2023-10-18T14:19:25.549171+00:00
2023-10-18T14:19:25.549191+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean winnerOfGame(String colors) {\n int aCnt=0, bCnt=0;\n int aTemp=0, bTemp=0;\n\n for(int i=0;i<colors.length();i++)\n {\n char c = colors.charAt(i);\n if(c==\'A\')\n {\n bTemp=0;\n aTemp+=1;\n if(aTemp>=3)\n {\n aCnt+=1;\n }\n }\n else\n {\n aTemp=0;\n bTemp+=1;\n if(bTemp>=3)\n {\n bCnt+=1;\n }\n }\n }\n return aCnt>bCnt;\n }\n}\n```
2
0
['Java']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
C++ Solution
c-solution-by-pranto1209-ywpm
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(
pranto1209
NORMAL
2023-10-05T09:05:47.502873+00:00
2023-10-05T09:05:47.502890+00:00
4
false
# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int alice = 0, bob = 0;\n for(int i = 1; i < colors.size() - 1; i++) {\n if(colors[i - 1] == \'A\' && colors[i] == \'A\' && colors[i + 1] == \'A\') alice++;\n if(colors[i - 1] == \'B\' && colors[i] == \'B\' && colors[i + 1] == \'B\') bob++;\n }\n if(alice > bob) return true;\n else return false;\n }\n};\n```
2
0
['C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Very easily understandable
very-easily-understandable-by-ritwik24-hox5
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
ritwik24
NORMAL
2023-10-03T15:40:43.488291+00:00
2023-10-03T15:40:43.488309+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int i=1,n=colors.size();\n int a=0,b=0;\n if(colors.size()<=2) return false;\n while(i<n)\n {\n if(colors[i+1]==\'A\' && colors[i]==\'A\' && colors[i-1]==\'A\')\n a+=1;\n if(colors[i+1]==\'B\' && colors[i]==\'B\' && colors[i-1]==\'B\')\n b+=1;\n i++;\n }return a>b;\n }\n};\n```
2
0
['C++']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
🔥🔥🔥Easiest Approach || O(n) time and O(1) space || beginner friendly solution 🔥🔥🔥
easiest-approach-on-time-and-o1-space-be-id18
Intuition\n Describe your first thoughts on how to solve this problem. \nTry to think as subarray problem having length >= 3.\n\n# Approach\n Describe your appr
pandeyashutosh02
NORMAL
2023-10-03T04:19:35.867194+00:00
2023-10-03T04:19:35.867218+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTry to think as subarray problem having length >= 3.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTake all the subarrays of A and B having length greater than or equal to 3 and store them into a final variable (totalA, totalB here in code) by subracting 2 from count sofar as 3 will give 1, 4 will give you 2, 5 will give 3 and so on.\nAnd these are the all possiblities of removing.\nIf final count of A\'s possiblities is less than or equal to count of B\' possiblities then return false according to question else return true.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the code is O(n), where n is the length of the input string colors. This is because there is a single loop that iterates through each character of the string once.\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1), constant space.\n\n# Code\n```\nclass Solution {\npublic:\n bool maxiAB(string colors) {\n int totalA=0, cur_maxA=0, cur_maxB=0, totalB=0;\n for(int i=0;i<colors.size();i++) {\n if(colors[i] == \'A\')cur_maxA++;\n if(i == colors.size()-1 || colors[i]==\'B\') {\n if(cur_maxA >= 3)totalA += cur_maxA-2;\n cur_maxA=0;\n }\n\n if(colors[i] == \'B\')cur_maxB++;\n if(i == colors.size()-1 || colors[i]==\'A\') {\n if(cur_maxB >= 3)totalB += cur_maxB-2;\n cur_maxB=0;\n }\n }\n return totalA<=totalB ? false : true;\n }\n\n bool winnerOfGame(string colors) {\n return maxiAB(colors);\n }\n};\n```
2
0
['C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
✅Simplest Solution 🤎 Y O U #TGM
simplest-solution-y-o-u-tgm-by-eliminate-hkvk
\n Describe your first thoughts on how to solve this problem. \n\n\n# Approach\n Describe your approach to solving the problem. \nStep-1 -> Intialize Alice and
EliminateCoding
NORMAL
2023-10-02T17:14:22.186339+00:00
2023-10-02T17:14:22.186371+00:00
17
false
\n<!-- Describe your first thoughts on how to solve this problem. -->\n<i>\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStep-1 -> Intialize Alice and Bob and iterate over input array from 1st index to last but one to avoid array index out of bounds exception \nStep-2 -> Start comparing previous current and next elements if all of them found \'A\' increment Alice, all of them found \'B\' increment Bob\nStep-3 -> Return true if Alice is greater than Bob (which means Alice won else return false)\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```\n// 16ms\nclass Solution {\n public boolean winnerOfGame(String s) {\n // AAA -> Alice++ || BBB ->> Bob++ return true if Alice win\n int Alice = 0;\n int Bob = 0;\n for(int i=1; i<s.length()-1; i++){\n if(s.charAt(i-1)==s.charAt(i) && s.charAt(i)==s.charAt(i+1)){\n if(s.charAt(i)==\'A\') Alice++;\n else Bob++;\n }\n }\n return Alice > Bob ? true : false;\n }\n}\n```\n```\n// 7ms\nclass Solution {\n public boolean winnerOfGame(String s) {\n // AAA -> Alice++ || BBB ->> Bob++ return true if Alice win\n int Alice = 0;\n int Bob = 0;\n int AliceTemp = 0;\n int BobTemp = 0;\n for(char ch : s.toCharArray()){\n if(ch==\'A\'){\n BobTemp = 0;\n AliceTemp++;\n if(AliceTemp >= 3) Alice++;\n }else{\n AliceTemp = 0;\n BobTemp++;\n if(BobTemp >= 3) Bob++;\n }\n }\n return Alice > Bob ? true : false;\n }\n}\n```
2
0
['String', 'Java']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
Simple Approach and Answer. No fancy code
simple-approach-and-answer-no-fancy-code-rjut
\n\n# Approach\n Describe your approach to solving the problem. \nSimply we can count the number of times Alice can pop and the number of times Bob can pop. And
siddd7
NORMAL
2023-10-02T17:04:14.234125+00:00
2023-10-02T17:04:51.014757+00:00
48
false
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSimply we can count the number of times Alice can pop and the number of times Bob can pop. And return whether Alice has the more count or not.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n a=b=0\n for i in range(1,len(colors)-1):\n if colors[i]==colors[i-1] and colors[i]==colors[i+1]:\n if colors[i]==\'A\':\n a+=1\n else:\n b+=1\n return a>b\n```
2
0
['Math', 'String', 'Greedy', 'Game Theory', 'Python3']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
🐍😱 Really Scary Python One-Liner! 🎃
really-scary-python-one-liner-by-galimov-zcxo
Faster than 98.94% of all solutions\n\n# Code\n\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n return sum((len(i) - 2)*(1 if i[0] i
galimovdv
NORMAL
2023-10-02T16:01:39.047460+00:00
2023-10-02T16:03:21.878197+00:00
143
false
**Faster than 98.94% of all solutions**\n\n# Code\n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n return sum((len(i) - 2)*(1 if i[0] is \'A\' else -1) for i in filter(lambda x: len(x) > 2, colors.replace(\'AB\', \'AxB\').replace(\'BA\', \'BxA\').split("x"))) > 0\n```
2
0
['Python3']
5
remove-colored-pieces-if-both-neighbors-are-the-same-color
✅☑[C++] || O(n) || Easiest Solutions || EXPLAINED🔥
c-on-easiest-solutions-explained-by-mark-3d7p
\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n\n# Approach\n(Also explained in the code)\n1. The function winnerOfGame takes a string colors as input, which repres
MarkSPhilip31
NORMAL
2023-10-02T15:43:44.179146+00:00
2023-10-02T15:43:44.179172+00:00
106
false
\n\n\n# *PLEASE UPVOTE IF IT HELPED*\n\n---\n\n# Approach\n***(Also explained in the code)***\n1. The function `winnerOfGame` takes a string `colors` as input, which represents a sequence of colors played in a game.\n\n1. It initializes `a` and `b` to zero. These variables are used to count the consecutive triplets of \'A\' and \'B\' colors, respectively.\n\n1. The loop iterates through the string starting from the second character (index 1) up to the second-to-last character (`index n - 2`).\n\n1. Inside the loop, it checks if there is a consecutive triplet of the same color. If so, it increments the count for the respective player (Alice or Bob).\n\n1. Finally, the function returns `true` if Alice (A) has more consecutive triplets than Bob (B), indicating that Alice wins; otherwise, it returns `false`, indicating that Bob wins.\n---\n\n# Complexity\n- **Time complexity:**\n$$O(n)$$\n\n- **Space complexity:**\n$$O(1)$$\n\n---\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int n = colors.size();\n\n if (n < 3) return false; // If the length of the string is less than 3, Bob wins.\n\n int a = 0; // Initialize the count of consecutive triplets for A\n int b = 0; // Initialize the count of consecutive triplets for B\n\n // Iterate through the string starting from the second character\n for (int i = 1; i < n - 1; i++) {\n // Check if there is a consecutive triplet (e.g., "AAA" or "BBB")\n if (colors[i] == colors[i - 1] && colors[i] == colors[i + 1]) {\n if (colors[i] == \'A\') a++; // Count consecutive triplets for A\n else if (colors[i] == \'B\') b++; // Count consecutive triplets for B\n }\n }\n\n return a > b; // Alice wins if she has more consecutive triplets than Bob\n }\n};\n\n\n\n```\n\n# *PLEASE UPVOTE IF IT HELPED*\n\n---\n\n---\n\n\n\n
2
0
['Math', 'String', 'Greedy', 'Game Theory', 'C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Most optimal solution with complete exaplanation
most-optimal-solution-with-complete-exap-n5og
\n# Approach\nThe solution iterates through the input string colors. For each position i, it checks if the character at that position and its neighboring charac
priyanshu11_
NORMAL
2023-10-02T12:55:04.195030+00:00
2023-10-02T12:55:04.195053+00:00
67
false
\n# Approach\nThe solution iterates through the input string colors. For each position i, it checks if the character at that position and its neighboring characters (at positions i-1 and i+1) satisfy the conditions mentioned in the game rules. If the conditions are met, Alice or Bob can make a move, and their corresponding counter (alice or bob) is incremented.\n\nFinally, the function compares the counts of valid moves made by Alice and Bob. If Alice has made more valid moves, the function returns true, indicating that Alice wins; otherwise, it returns false, indicating that Bob wins.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n```java []\nclass Solution {\n public boolean winnerOfGame(String colors) {\n int alice = 0, bob = 0;\n for (int i = 1; i < colors.length() - 1; i++) {\n char next = colors.charAt(i + 1);\n char prev = colors.charAt(i - 1);\n char curr = colors.charAt(i);\n if (curr == \'A\' && next == \'A\' && prev == \'A\') {\n alice++;\n }\n if (curr == \'B\' && next == \'B\' && prev == \'B\') {\n bob++;\n }\n }\n return alice > bob;\n }\n}\n\n```\n```python3 []\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n alice, bob = 0, 0\n for i in range(1, len(colors) - 1):\n next_char = colors[i + 1]\n prev_char = colors[i - 1]\n curr_char = colors[i]\n if curr_char == \'A\' and next_char == \'A\' and prev_char == \'A\':\n alice += 1\n if curr_char == \'B\' and next_char == \'B\' and prev_char == \'B\':\n bob += 1\n return alice > bob\n\n```\n```C++ []\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int alice = 0, bob = 0;\n for(int i = 1; i< colors.size()-1; i++) {\n char next = colors[i+1];\n char prev = colors[i-1];\n char curr = colors[i];\n if(curr == \'A\' && next == \'A\' && prev == \'A\') alice++;\n if(curr == \'B\' && next == \'B\' && prev == \'B\') bob++;\n }\n return alice>bob;\n }\n};\n```\n
2
0
['Math', 'String', 'Greedy', 'Game Theory', 'Python', 'C++', 'Java', 'Python3']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
simple solution
simple-solution-by-hrushikeshmahajan044-k44e
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
HrushikeshMahajan044
NORMAL
2023-10-02T10:48:15.116709+00:00
2023-10-02T10:48:15.116732+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n if(colors.size()>=100000){\n int cntA=0, cntB=0;\n for(int i=0;i<colors.size();i++){\n if(colors[i]==\'A\')cntA++;\n if(colors[i]==\'B\')cntB++;\n }\n return cntA>cntB;\n }\n while(true){\n if(colors.size()<3)return false;\n for(int i=1;i<colors.size()-1;i++){\n if(colors[i]==\'A\' && colors[i+1]==\'A\' && colors[i-1]==\'A\'){\n colors.erase(colors.begin()+i);\n break;\n }\n else if(i==colors.size()-2) return false;\n }\n if(colors.size()<3)return true;\n for(int i=1;i<colors.size()-1;i++){\n if(colors[i]==\'B\' && colors[i+1]==\'B\' && colors[i-1]==\'B\'){\n colors.erase(colors.begin()+i);\n break;\n }\n else if(i==colors.size()-2) return true;\n }\n }\n return false;\n }\n};\n```
2
0
['C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
✅100%🔥Kotlin🔥Easy Solution
100kotlineasy-solution-by-umairzahid907-4zk3
Intuition\nThe goal is to determine the winner of the game where Alice and Bob take alternating turns removing pieces with specific color conditions. Alice can
umairzahid907
NORMAL
2023-10-02T10:29:30.120324+00:00
2023-10-02T10:29:30.120348+00:00
10
false
# Intuition\nThe goal is to determine the winner of the game where Alice and Bob take alternating turns removing pieces with specific color conditions. Alice can only remove a piece colored \'A\' if both of its neighbors are also \'A\', and Bob can only remove a piece colored \'B\' under the same condition. The player who cannot make a move on their turn loses the game. To find the winner, we count consecutive \'A\'s and \'B\'s in the string and compare the counts.\n# Approach\n1. Calculate the length of the input string `n`.\n2. If `n` is less than or equal to 2, return false because there are not enough pieces to play the game.\n3. Initialize variables `count_alice` and `count_bob` to keep track of valid moves for Alice and Bob, respectively.\n4. Initialize variables `count_A` and `count_B` to count consecutive \'A\'s and \'B\'s.\n5. Iterate through the string from left to right:\n - If the current character is \'A\':\n - Increment `count_A` and reset `count_B` to 0.\n - If `count_A` reaches 3 or more, increment `count_alice`.\n - If the current character is \'B\':\n - Increment `count_B` and reset `count_A` to 0.\n - If `count_B` reaches 3 or more, increment `count_bob`.\n6. After the loop, compare `count_alice` and `count_bob` to determine the winner.\n - If `count_alice` is greater than `count_bob`, return true, indicating Alice wins.\n - Otherwise, return false, indicating Bob wins or it\'s a draw.\n\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n fun winnerOfGame(colors: String): Boolean {\n val n = colors.length\n if(n<=2){\n return false\n }\n var count_alice = 0\n var count_bob = 0\n var count_A = 0\n var count_B = 0\n for(i in 0 until n){\n if(colors[i] == \'A\'){\n count_A++\n count_B = 0\n if(count_A >= 3) count_alice++\n }else{\n count_B++ \n count_A = 0\n if(count_B >= 3) count_bob++\n }\n \n }\n if(count_alice > count_bob){\n return true\n }else{\n return false\n }\n }\n}\n```
2
0
['Kotlin']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Easy solution with single counter || Beats 99.52% from memory usage || Python
easy-solution-with-single-counter-beats-xht81
Code\n\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n c = 0\n\n for i in range(1, len(colors)-1):\n if colors[i-1
sheshan25
NORMAL
2023-10-02T08:22:11.693631+00:00
2023-10-02T08:23:15.781457+00:00
19
false
# Code\n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n c = 0\n\n for i in range(1, len(colors)-1):\n if colors[i-1]=="A" and colors[i]=="A" and colors[i+1]=="A":\n c +=1\n elif colors[i-1]=="B" and colors[i]=="B" and colors[i+1]=="B":\n c -= 1\n\n if c>0:\n return True\n return False\n```
2
0
['Math', 'String', 'Greedy', 'Game Theory', 'Python3']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Easy Python solution with Explanation | O(n) O(1) Beats 99.93%
easy-python-solution-with-explanation-on-9cjf
\n# Approach\n Describe your approach to solving the problem. \nSince we need to have 3 A\'s or 3 B\'s in a sequence, We will first calculate the number of thos
ramakrishna1607
NORMAL
2023-10-02T06:17:43.475616+00:00
2023-10-02T06:17:43.475647+00:00
6
false
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSince we need to have 3 A\'s or 3 B\'s in a sequence, We will first calculate the number of those occurences.\nBut if the given string length is less than 3, there is no possibility of starting the game. So we return False\nWe now compare the number of occurances of the A\'s and B\'s \nand return True if Alice is winning (when the A\'s count is greater than B\'s count)\nand return Flase otherwise\n\n## Note\n When I say Occurances of A\'s and B\'s, I mean the AAA or BBB.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n if len(colors)<3:\n return False\n a_count=0\n b_count=0\n for i in range(len(colors)-2):\n if colors[i]==colors[i+1]==colors[i+2]=="A":\n a_count+=1\n elif colors[i]==colors[i+1]==colors[i+2]=="B":\n b_count+=1\n if a_count>b_count:\n return True\n elif a_count>b_count:\n return False\n```
2
0
['Python3']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
🔥 C++ Solution || O(n) time and O(1) space || Greedy approach
c-solution-on-time-and-o1-space-greedy-a-coq4
\n# Code\n\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int aliceTurns = 0, bobTurns = 0;\n int n = colors.size();\n\n
ravi_verma786
NORMAL
2023-10-02T06:05:27.860476+00:00
2023-10-02T06:05:27.860495+00:00
51
false
\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int aliceTurns = 0, bobTurns = 0;\n int n = colors.size();\n\n for(int i=2;i<n;i++){\n if(colors[i] == \'A\' && colors[i-1] == \'A\' && colors[i-2] == \'A\'){\n aliceTurns++;\n }\n else if(colors[i] == \'B\' && colors[i-1] == \'B\' && colors[i-2] == \'B\'){\n bobTurns++;\n }\n }\n\n return aliceTurns > bobTurns;\n }\n};\n```
2
0
['String', 'Greedy', 'C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
✅ Easy and straightforward || One Loop 🔁, Indicators 🚦 || and animation 🎮"
easy-and-straightforward-one-loop-indica-w3tp
Intuition\n\n\n\n# Approach\n Describe your approach to solving the problem. \n1. Initialize three variables: am and bm to keep track of the scores of players A
Tyrex_19
NORMAL
2023-10-02T05:53:25.115999+00:00
2023-10-02T07:18:43.528559+00:00
29
false
# Intuition\n![ezgif.com-video-to-gif (11).gif](https://assets.leetcode.com/users/images/f467437b-101c-49f5-a320-7e2d38f751e5_1696229474.0028176.gif)\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize three variables: **am** and **bm** to keep track of the scores of players A and B respectively, and **li** to keep track of the last index of a different color.\n\n1. Assign the first character of the colors string to the variable first. This character represents the color of the first ball in the game.\n\n1. Start a loop that iterates over the indices of the colors string, from 0 to colors.size() (inclusive).\n\n 1. Inside the loop, check if the current index i is equal to the size of the colors string or if the color at index i is different from the color at the first index (first). This condition checks if the current ball has a different color than the previous ones.\n\n 1. If the condition is true, calculate the score for the previous sequence of balls and update the corresponding player\'s score. The score is calculated by taking the maximum of 0 and the difference between the current index i, the last index li, and 2. This ensures that only sequences of at least 3 balls contribute to the score.\n\n 1. Update the last index li to the current index i, indicating the end of the previous sequence.\n\n 1. Update the first variable to the color of the new sequence of balls starting at index li.\n\n1. After the loop, compare the scores of players A and B. If player A\'s score (am) is greater than player B\'s score (bm), return true indicating that player A is the winner. Otherwise, return false indicating that player B is the winner.\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 bool winnerOfGame(string colors) {\n int am = 0, bm = 0, li = 0;\n char first = colors[0];\n\n for(int i = 0; i <= colors.size(); i++){\n if(i == colors.size() || colors[i] != first){\n if(first == \'A\') am += max(0, i - li - 2);\n else bm += max(0, i - li - 2);\n li = i;\n first = colors[li];\n \n }\n }\n \n return am > bm;\n }\n};\n```\n\nhttps://youtu.be/vd8UenMAPAE
2
0
['C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
#3_Line Solution For Begginers simple One With explanation ✔️✔️✅
3_line-solution-for-begginers-simple-one-l6ii
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\ncount the Alice\'s play and Bob\'s play is alice\'s turn is greater then
nandunk
NORMAL
2023-10-02T05:01:02.668478+00:00
2023-10-02T05:01:02.668503+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\ncount the Alice\'s play and Bob\'s play is alice\'s turn is greater then he win else he lose the game \n# Complexity\n- Time complexity:\n $$O(n)$$ -\n\n- Space complexity:\n$$O(1)$$ \n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string c) {\n int cnt1=0,cnt2=0;\n for(int i=1;i<c.size()-1;i++){\n if(c[i-1]==\'A\' &&c[i]==\'A\' && c[i+1]==\'A\') cnt1++;\n if(c[i-1]==\'B\' &&c[i]==\'B\' && c[i+1]==\'B\') cnt2++;\n }\n return cnt1>cnt2;\n }\n};\n```
2
0
['C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
🔥Beats 100% | ✅ Line by Line Expl. | [PY/Java/C++/C#/C/JS/Rust/Go]
beats-100-line-by-line-expl-pyjavacccjsr-1blo
python []\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n totalA = 0 # Initialize a variable to store the total points of player A.
Neoni_77
NORMAL
2023-10-02T04:48:07.235486+00:00
2023-10-02T04:48:07.235520+00:00
345
false
```python []\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n totalA = 0 # Initialize a variable to store the total points of player A.\n totalB = 0 # Initialize a variable to store the total points of player B.\n currA = 0 # Initialize a variable to count the current consecutive colors of A.\n currB = 0 # Initialize a variable to count the current consecutive colors of B.\n\n # Iterate through the characters in the \'colors\' string.\n for char in colors:\n if char == \'A\': # If the current character is \'A\':\n currA += 1 # Increment the count of consecutive \'A\' colors.\n if currB > 2: # If there were more than 2 consecutive \'B\' colors before this \'A\':\n totalB += currB - 2 # Add the excess consecutive \'B\' colors to totalB.\n currB = 0 # Reset the consecutive \'B\' count since there\'s an \'A\'.\n else: # If the current character is \'B\':\n currB += 1 # Increment the count of consecutive \'B\' colors.\n if currA > 2: # If there were more than 2 consecutive \'A\' colors before this \'B\':\n totalA += currA - 2 # Add the excess consecutive \'A\' colors to totalA.\n currA = 0 # Reset the consecutive \'A\' count since there\'s a \'B\'.\n\n # After the loop, add any remaining consecutive \'A\' and \'B\' colors to their respective totals.\n if currA > 2:\n totalA += currA - 2\n if currB > 2:\n totalB += currB - 2\n\n # Compare the total points for \'A\' and \'B\' to determine the winner.\n return totalA > totalB # If \'A\' has more points, return True (A wins); otherwise, return False (B wins or it\'s a tie).\n\n```\n```Java []\npublic class Solution {\n public boolean winnerOfGame(String colors) {\n int totalA = 0; // Initialize a variable to store the total points of player A.\n int totalB = 0; // Initialize a variable to store the total points of player B.\n int currA = 0; // Initialize a variable to count the current consecutive colors of A.\n int currB = 0; // Initialize a variable to count the current consecutive colors of B.\n\n // Iterate through the characters in the \'colors\' string.\n for (char c : colors.toCharArray()) {\n if (c == \'A\') { // If the current character is \'A\':\n currA++; // Increment the count of consecutive \'A\' colors.\n if (currB > 2) // If there were more than 2 consecutive \'B\' colors before this \'A\':\n totalB += currB - 2; // Add the excess consecutive \'B\' colors to totalB.\n currB = 0; // Reset the consecutive \'B\' count since there\'s an \'A\'.\n } else { // If the current character is \'B\':\n currB++; // Increment the count of consecutive \'B\' colors.\n if (currA > 2) // If there were more than 2 consecutive \'A\' colors before this \'B\':\n totalA += currA - 2; // Add the excess consecutive \'A\' colors to totalA.\n currA = 0; // Reset the consecutive \'A\' count since there\'s a \'B\'.\n }\n }\n\n // After the loop, add any remaining consecutive \'A\' and \'B\' colors to their respective totals.\n if (currA > 2)\n totalA += currA - 2;\n if (currB > 2)\n totalB += currB - 2;\n\n // Compare the total points for \'A\' and \'B\' to determine the winner.\n return totalA > totalB; // If \'A\' has more points, return true (A wins); otherwise, return false (B wins or it\'s a tie).\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int totalA = 0, totalB = 0; // Initialize counters for the total points of players A and B.\n int currA = 0, currB = 0; // Initialize counters for the current consecutive colors of A and B.\n\n // Iterate through the characters in the \'colors\' string.\n for (int i = 0; i < colors.size(); i++) {\n if (colors[i] == \'A\') { // If the current character is \'A\':\n currA++; // Increment the count of consecutive \'A\' colors.\n if (currB > 2) // If there were more than 2 consecutive \'B\' colors before this \'A\':\n totalB += currB - 2; // Add the excess consecutive \'B\' colors to totalB.\n currB = 0; // Reset the consecutive \'B\' count since there\'s an \'A\'.\n } else { // If the current character is \'B\':\n currB++; // Increment the count of consecutive \'B\' colors.\n if (currA > 2) // If there were more than 2 consecutive \'A\' colors before this \'B\':\n totalA += currA - 2; // Add the excess consecutive \'A\' colors to totalA.\n currA = 0; // Reset the consecutive \'A\' count since there\'s a \'B\'.\n }\n }\n\n // After the loop, add any remaining consecutive \'A\' and \'B\' colors to their respective totals.\n if (currA > 2)\n totalA += currA - 2;\n if (currB > 2)\n totalB += currB - 2;\n\n // Compare the total points for \'A\' and \'B\' to determine the winner.\n if (totalA > totalB)\n return true; // If \'A\' has more points, return true (A wins).\n return false; // Otherwise, return false (B wins or it\'s a tie).\n }\n};\n\n```\n```C# []\npublic class Solution {\n public bool WinnerOfGame(string colors) {\n int totalA = 0; // Initialize a variable to store the total points of player A.\n int totalB = 0; // Initialize a variable to store the total points of player B.\n int currA = 0; // Initialize a variable to count the current consecutive colors of A.\n int currB = 0; // Initialize a variable to count the current consecutive colors of B.\n\n // Iterate through the characters in the \'colors\' string.\n foreach (char c in colors) {\n if (c == \'A\') { // If the current character is \'A\':\n currA++; // Increment the count of consecutive \'A\' colors.\n if (currB > 2) // If there were more than 2 consecutive \'B\' colors before this \'A\':\n totalB += currB - 2; // Add the excess consecutive \'B\' colors to totalB.\n currB = 0; // Reset the consecutive \'B\' count since there\'s an \'A\'.\n } else { // If the current character is \'B\':\n currB++; // Increment the count of consecutive \'B\' colors.\n if (currA > 2) // If there were more than 2 consecutive \'A\' colors before this \'B\':\n totalA += currA - 2; // Add the excess consecutive \'A\' colors to totalA.\n currA = 0; // Reset the consecutive \'A\' count since there\'s a \'B\'.\n }\n }\n\n // After the loop, add any remaining consecutive \'A\' and \'B\' colors to their respective totals.\n if (currA > 2)\n totalA += currA - 2;\n if (currB > 2)\n totalB += currB - 2;\n\n // Compare the total points for \'A\' and \'B\' to determine the winner.\n return totalA > totalB; // If \'A\' has more points, return true (A wins); otherwise, return false (B wins or it\'s a tie).\n }\n}\n\n```\n```C []\n#include <stdbool.h> // Include the header for boolean data type.\n\nbool winnerOfGame(char *colors) {\n int totalA = 0; // Initialize a variable to store the total points of player A.\n int totalB = 0; // Initialize a variable to store the total points of player B.\n int currA = 0; // Initialize a variable to count the current consecutive colors of A.\n int currB = 0; // Initialize a variable to count the current consecutive colors of B.\n\n // Iterate through the characters in the \'colors\' string.\n for (int i = 0; colors[i] != \'\\0\'; i++) {\n char currentChar = colors[i];\n if (currentChar == \'A\') { // If the current character is \'A\':\n currA++; // Increment the count of consecutive \'A\' colors.\n if (currB > 2) // If there were more than 2 consecutive \'B\' colors before this \'A\':\n totalB += currB - 2; // Add the excess consecutive \'B\' colors to totalB.\n currB = 0; // Reset the consecutive \'B\' count since there\'s an \'A\'.\n } else { // If the current character is \'B\':\n currB++; // Increment the count of consecutive \'B\' colors.\n if (currA > 2) // If there were more than 2 consecutive \'A\' colors before this \'B\':\n totalA += currA - 2; // Add the excess consecutive \'A\' colors to totalA.\n currA = 0; // Reset the consecutive \'A\' count since there\'s a \'B\'.\n }\n }\n\n // After the loop, add any remaining consecutive \'A\' and \'B\' colors to their respective totals.\n if (currA > 2)\n totalA += currA - 2;\n if (currB > 2)\n totalB += currB - 2;\n\n // Compare the total points for \'A\' and \'B\' to determine the winner.\n return totalA > totalB; // If \'A\' has more points, return true (A wins); otherwise, return false (B wins or it\'s a tie).\n}\n\n```\n```JavaScript []\nclass Solution {\n winnerOfGame(colors) {\n let totalA = 0; // Initialize a variable to store the total points of player A.\n let totalB = 0; // Initialize a variable to store the total points of player B.\n let currA = 0; // Initialize a variable to count the current consecutive colors of A.\n let currB = 0; // Initialize a variable to count the current consecutive colors of B.\n\n // Iterate through the characters in the \'colors\' string.\n for (let i = 0; i < colors.length; i++) {\n const char = colors[i];\n if (char === \'A\') { // If the current character is \'A\':\n currA++; // Increment the count of consecutive \'A\' colors.\n if (currB > 2) { // If there were more than 2 consecutive \'B\' colors before this \'A\':\n totalB += currB - 2; // Add the excess consecutive \'B\' colors to totalB.\n }\n currB = 0; // Reset the consecutive \'B\' count since there\'s an \'A\'.\n } else { // If the current character is \'B\':\n currB++; // Increment the count of consecutive \'B\' colors.\n if (currA > 2) { // If there were more than 2 consecutive \'A\' colors before this \'B\':\n totalA += currA - 2; // Add the excess consecutive \'A\' colors to totalA.\n }\n currA = 0; // Reset the consecutive \'A\' count since there\'s a \'B\'.\n }\n }\n\n // After the loop, add any remaining consecutive \'A\' and \'B\' colors to their respective totals.\n if (currA > 2) {\n totalA += currA - 2;\n }\n if (currB > 2) {\n totalB += currB - 2;\n }\n\n // Compare the total points for \'A\' and \'B\' to determine the winner.\n return totalA > totalB; // If \'A\' has more points, return true (A wins); otherwise, return false (B wins or it\'s a tie).\n }\n}\n\n```\n```Rust []\nstruct Solution;\n\nimpl Solution {\n pub fn winner_of_game(colors: &str) -> bool {\n let mut total_a = 0; // Initialize a variable to store the total points of player A.\n let mut total_b = 0; // Initialize a variable to store the total points of player B.\n let mut curr_a = 0; // Initialize a variable to count the current consecutive colors of A.\n let mut curr_b = 0; // Initialize a variable to count the current consecutive colors of B.\n\n // Iterate through the characters in the \'colors\' string.\n for char in colors.chars() {\n if char == \'A\' { // If the current character is \'A\':\n curr_a += 1; // Increment the count of consecutive \'A\' colors.\n if curr_b > 2 { // If there were more than 2 consecutive \'B\' colors before this \'A\':\n total_b += curr_b - 2; // Add the excess consecutive \'B\' colors to total_b.\n }\n curr_b = 0; // Reset the consecutive \'B\' count since there\'s an \'A\'.\n } else { // If the current character is \'B\':\n curr_b += 1; // Increment the count of consecutive \'B\' colors.\n if curr_a > 2 { // If there were more than 2 consecutive \'A\' colors before this \'B\':\n total_a += curr_a - 2; // Add the excess consecutive \'A\' colors to total_a.\n }\n curr_a = 0; // Reset the consecutive \'A\' count since there\'s a \'B\'.\n }\n }\n\n // After the loop, add any remaining consecutive \'A\' and \'B\' colors to their respective totals.\n if curr_a > 2 {\n total_a += curr_a - 2;\n }\n if curr_b > 2 {\n total_b += curr_b - 2;\n }\n\n // Compare the total points for \'A\' and \'B\' to determine the winner.\n total_a > total_b // If \'A\' has more points, return true (A wins); otherwise, return false (B wins or it\'s a tie).\n }\n}\n\nfn main() {\n let colors = "AABBBBAAABBAA"; // Example input string.\n let result = Solution::winner_of_game(colors);\n println!("Is player A the winner? {}", result);\n}\n\n```\n```Go []\npackage main\n\nimport "fmt"\n\nfunc winnerOfGame(colors string) bool {\n\ttotalA := 0 // Initialize a variable to store the total points of player A.\n\ttotalB := 0 // Initialize a variable to store the total points of player B.\n\tcurrA := 0 // Initialize a variable to count the current consecutive colors of A.\n\tcurrB := 0 // Initialize a variable to count the current consecutive colors of B.\n\n\t// Iterate through the characters in the \'colors\' string.\n\tfor _, char := range colors {\n\t\tif char == \'A\' { // If the current character is \'A\':\n\t\t\tcurrA++ // Increment the count of consecutive \'A\' colors.\n\t\t\tif currB > 2 { // If there were more than 2 consecutive \'B\' colors before this \'A\':\n\t\t\t\ttotalB += currB - 2 // Add the excess consecutive \'B\' colors to totalB.\n\t\t\t}\n\t\t\tcurrB = 0 // Reset the consecutive \'B\' count since there\'s an \'A\'.\n\t\t} else { // If the current character is \'B\':\n\t\t\tcurrB++ // Increment the count of consecutive \'B\' colors.\n\t\t\tif currA > 2 { // If there were more than 2 consecutive \'A\' colors before this \'B\':\n\t\t\t\ttotalA += currA - 2 // Add the excess consecutive \'A\' colors to totalA.\n\t\t\t}\n\t\t\tcurrA = 0 // Reset the consecutive \'A\' count since there\'s a \'B\'.\n\t\t}\n\t}\n\n\t// After the loop, add any remaining consecutive \'A\' and \'B\' colors to their respective totals.\n\tif currA > 2 {\n\t\ttotalA += currA - 2\n\t}\n\tif currB > 2 {\n\t\ttotalB += currB - 2\n\t}\n\n\t// Compare the total points for \'A\' and \'B\' to determine the winner.\n\treturn totalA > totalB // If \'A\' has more points, return true (A wins); otherwise, return false (B wins or it\'s a tie).\n}\n\nfunc main() {\n\tcolors := "AAABBB"\n\tresult := winnerOfGame(colors)\n\tfmt.Println(result) // Output: true (A wins)\n}\n\n```
2
0
['C', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript', 'C#']
2
remove-colored-pieces-if-both-neighbors-are-the-same-color
✅"2" Lines of Code with "2" Step Explanation❤️💯🔥
2-lines-of-code-with-2-step-explanation-1rzl9
Approach\nStep 1: Initialization and Loop\n- Two integer variables a and b are initialized to 0. These variables will be used to keep track of the number of con
ReddySaiNitishSamudrala
NORMAL
2023-10-02T04:08:27.621673+00:00
2023-10-02T04:08:27.621699+00:00
19
false
# Approach\nStep 1: Initialization and Loop\n- Two integer variables `a` and `b` are initialized to 0. These variables will be used to keep track of the number of consecutive triplets \'AAA\' and \'BBB\' in the input string `s`, respectively.\n- The code then enters a `for` loop that iterates over the characters of the string `s` starting from the second character (index 1) up to the second-to-last character (index `s.length() - 2`). It stops at the second-to-last character because it\'s checking triplets of characters (i-1, i, i+1), so the loop stops one character before the end of the string.\n\nStep 2: Counting Triplets and Determining the Winner\n- Within the loop, there is an `if` statement that checks the following condition:\n - If the current character at index `i` is equal to both the previous character at index `i-1` and the next character at index `i+1`, i.e., it\'s part of a triplet like \'XXX\' (where \'X\' can be \'A\' or \'B\'), then it checks the character itself to see if it\'s \'A\' or \'B\'.\n - If the current character is \'A\', it increments the count `a` by 1. This checks for consecutive triplets of \'AAA\'.\n - If the current character is \'B\', it increments the count `b` by 1. This checks for consecutive triplets of \'BBB\'.\n- After the loop, it compares the counts `a` and `b`.\n - If `a` is greater than `b`, it means that player A has more consecutive \'AAA\' triplets and returns `true`, indicating that player A is the winner.\n - Otherwise, it returns `false`, indicating that player B is the winner or it\'s a tie if `b` is greater than or equal to `a`.\n# Complexity\n- Time complexity:O(n)\n- Space complexity:O(1)\n# Code\n```\nclass Solution {\n public boolean winnerOfGame(String s) {\n int a=0;\n int b=0;\n for(int i=1;i<s.length()-1;i++){\n if(s.charAt(i)==s.charAt(i-1) && s.charAt(i)==s.charAt(i+1)){\n if(s.charAt(i)==\'A\'){\n a++;\n }\n else{\n b++;\n }\n }\n }\n if(a>b){\n return true;\n }\n return false;\n }\n}\n\n```
2
0
['Java']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
Bests Java Solution || Beats 80%
bests-java-solution-beats-80-by-ravikuma-9exq
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ravikumar50
NORMAL
2023-10-02T03:41:30.347319+00:00
2023-10-02T03:41:30.347346+00:00
391
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n\n public boolean winnerOfGame(String s) {\n int n = s.length();\n if(n<=2) return false;\n\n int A = 0;\n int B = 0;\n\n for(int i=1; i<n-1; i++){\n char ch = s.charAt(i);\n char a = s.charAt(i-1);\n char b = s.charAt(i+1);\n if(ch==\'A\' && ch==a && ch==b) A++;\n if(ch==\'B\' && ch==a && ch==b) B++;\n }\n if(A>B) return true;\n else return false;\n }\n}\n```
2
0
['Java']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
O(n) time O(1) space solution greedy
on-time-o1-space-solution-greedy-by-saks-a25u
Intuition\n Describe your first thoughts on how to solve this problem. \n\nAfter seeing the question the first thing that comes to mind is number of moves for a
sakshamag_16
NORMAL
2023-10-02T03:36:05.132301+00:00
2023-10-02T03:36:05.132323+00:00
32
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nAfter seeing the question the first thing that comes to mind is number of moves for alice should be greater than number of moves Bob for ALice to win. Hence we need to find number of moves of both the players.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nNow since we can see 3 A can make 1 move and after that if there are extra A\'s then it will combine with the 2 A\'s that were remaining. Hence that should also be counted as 1 move. \nSimilarly for Bob we will find moves. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\nTime Complexity - O(n) for traversing the string.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nSpace Complexity - O(1)\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int countA=0,countB=0,movesA=0,movesB=0;\n\n for(int i=0;i<colors.length();i++){\n if(colors[i]==\'A\'){\n countA++;\n if(countA>=3){\n movesA++;\n }\n countB=0;\n }\n if(colors[i]==\'B\'){\n countB++;\n if(countB>=3){\n movesB++;\n }\n countA=0;\n }\n }\n return movesA>movesB;\n }\n};\n```
2
0
['Math', 'Greedy', 'C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
🐢Slow and Unintuitive Python Solution | Slower than 95%🐢
slow-and-unintuitive-python-solution-slo-qy77
\nThe top solution explains how this game is not very complicated and you can determine the winner by counting the number of As and Bs. This is like a more comp
JeliHacker
NORMAL
2023-10-02T02:21:02.982913+00:00
2023-10-02T02:21:02.982939+00:00
61
false
\nThe top solution explains how this game is not very complicated and you can determine the winner by counting the number of As and Bs. This is like a more complicated version of that solution.\uD83D\uDE0E \n\n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n count = 0 # 0 if Alice\'s turn, 1 if it is Bob\'s turn\n\n chunks = []\n i = 0\n # we start by breaking the input into groups of As and Bs\n while i < len(colors):\n new_chunk = [colors[i]]\n while i < len(colors) - 1 and colors[i + 1] == colors[i]:\n i += 1\n new_chunk.append(colors[i])\n\n if new_chunk:\n chunks.append(new_chunk)\n i += 1\n\n # We filter the chunks into valid chunks, which contain\n # three or more of a color\n alice_valid_chunks = [chunk for chunk in chunks if chunk[0] == "A" and len(chunk) > 2]\n bob_valid_chunks = [chunk for chunk in chunks if chunk[0] == "B" and len(chunk) > 2]\n \n # we simulate the game.\n for i in range(len(colors)):\n if count == 0: # Alice\'s turn\n if alice_valid_chunks and len(alice_valid_chunks[-1]) > 2:\n alice_valid_chunks[-1].pop()\n if len(alice_valid_chunks[-1]) < 3:\n alice_valid_chunks.pop()\n else: # she has run out of moves\n return False\n else: # Bob\'s turn\n if bob_valid_chunks and len(bob_valid_chunks[-1]) > 2:\n bob_valid_chunks[-1].pop()\n if len(bob_valid_chunks[-1]) < 3:\n bob_valid_chunks.pop()\n else: # he has run out of moves\n return True\n \n count ^= 1\n \n return False\n```
2
0
['Python3']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
Beats 96.22% in speed || Two Pointer Approach || Very Short
beats-9622-in-speed-two-pointer-approach-c466
Intuition\nThe code appears to be implementing a function winnerOfGame that takes a string colors as input. This function aims to determine the winner of a game
NinjaFire
NORMAL
2023-10-02T02:17:40.178897+00:00
2023-10-02T02:18:29.918533+00:00
186
false
# Intuition\nThe code appears to be implementing a function winnerOfGame that takes a string colors as input. This function aims to determine the winner of a game based on certain rules related to consecutive color sequences.\n\n# Approach\nThe code uses a while loop to iterate over the characters of the colors string. Within this loop, there is another while loop that starts at the current position i and continues until it encounters a different color. This inner loop helps in finding consecutive sequences of the same color.\n\nInside the inner loop, it calculates the length of the consecutive sequence (turn). If this length is greater than or equal to 3, it subtracts 2 from it (as per the game rules), otherwise, it sets turn to 0.\n\nThe code then updates the score of player A or player B based on the current color and the calculated turn value.\n\nFinally, after processing the entire string, it checks whether the score of player A (a) is greater than player B (b) and returns the result.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int a = 0, b = 0, j = 0, i = 0;\n while(i < colors.size()) {\n j = i;\n while (j < colors.size() && colors[j] == colors[i]) j++;\n int turn = (j - i) >= 3 ? (j - i) - 2 : 0;\n colors[i] == \'A\' ? a += turn : b += turn;\n i = j;\n }\n return a > b;\n }\n};\n```
2
0
['Two Pointers', 'String', 'Counting', 'Game Theory', 'C++']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
Easy to understand.
easy-to-understand-by-mukeshgupta-7k9j
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach Using Loop.\n Describe your approach to solving the problem. \n\n# Complex
mukeshgupta_
NORMAL
2023-10-02T00:46:36.934465+00:00
2023-10-02T00:46:36.934484+00:00
5
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach Using Loop.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean winnerOfGame(String colors) {\n int n = colors.length();\n int aliceCount = 0;\n int bobCount = 0;\n\n for (int i = 1; i < n - 1; i++) {\n if (colors.charAt(i - 1) == \'A\' && colors.charAt(i) == \'A\' && colors.charAt(i + 1) == \'A\') {\n aliceCount++;\n } else if (colors.charAt(i - 1) == \'B\' && colors.charAt(i) == \'B\' && colors.charAt(i + 1) == \'B\') {\n bobCount++;\n }\n }\n\n return aliceCount > bobCount;\n }\n}\n\n```
2
0
['Java']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
3'A >3'B Solution...
3a-3b-solution-by-striver_011-i6ru
Intuition\n Describe your first thoughts on how to solve this problem. \nThe thing is to obsever the three consecutive A\'s && B\'s hence the turn will take one
striver_011
NORMAL
2023-05-26T14:00:33.007896+00:00
2023-05-26T14:00:33.007941+00:00
487
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe thing is to obsever the three consecutive A\'s && B\'s hence the turn will take one by one right..! hence the count of consecutive A\'s are greater than the consecutive B\'s then definately Alice win which of consecutive A\'s right..!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n*Count the 3 Consecutive A\'s and 3 consecutive B\'s\n*if **(3Consecutive of A\'s )> (3Consecutive B\'s)** return true else return false;\n\n# Complexity\n- Time complexity:\n- O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int a=0,b=0;\n if(colors.size()>2){\n for(int i=0;i<colors.size()-2;i++){\n if(colors[i]==\'A\' && colors[i+1]==\'A\' && colors[i+2]==\'A\') a++;\n if(colors[i]==\'B\' && colors[i+1]==\'B\' && colors[i+2]==\'B\') b++; } \n }\n return (a<=b) ? false : true;\n \n \n }\n};\n```
2
1
['C++']
3
remove-colored-pieces-if-both-neighbors-are-the-same-color
2 solutions | Counting & Stack | C++
2-solutions-counting-stack-c-by-tusharbh-e7cd
Counting\n\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n long long cntA = 0, cntB = 0, alice = 0, bob = 0;\n for(char c : c
TusharBhart
NORMAL
2023-03-25T11:04:31.980457+00:00
2023-03-25T11:04:31.980488+00:00
802
false
# Counting\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n long long cntA = 0, cntB = 0, alice = 0, bob = 0;\n for(char c : colors) {\n if(c == \'A\') {\n cntA++;\n if(cntA >= 3) alice += cntA - 2;\n cntB = 0;\n }\n else {\n cntB++;\n if(cntB >= 3) bob += cntB - 2;\n cntA = 0;\n }\n }\n return alice > bob;\n }\n};\n```\n\n# Stack\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int bob = 0, alice = 0;\n stack<char> s;\n for(char c : colors) {\n if(s.size() >= 2) {\n char first = s.top(); s.pop();\n char second = s.top(); s.pop();\n s.push(second);\n s.push(first);\n if(c == first && c == second) {\n c == \'A\' ? alice++ : bob++;\n }\n else s.push(c);\n }\n else s.push(c);\n }\n return alice > bob;\n }\n};\n\n```
2
0
['Stack', 'Counting', 'C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Cpp Solution O(n) || Simple Solution
cpp-solution-on-simple-solution-by-indom-nyem
Intuition\nCount the Number of "AAA" and "BBB"\n\n# Approach\n-> Count number of "AAA" and "BBB" and store them in a variable\n\n-> If count of "AAA" is more th
Indominous1
NORMAL
2022-11-08T10:22:55.066787+00:00
2022-11-17T19:08:45.393112+00:00
592
false
# Intuition\nCount the Number of "AAA" and "BBB"\n\n# Approach\n-> Count number of "AAA" and "BBB" and store them in a variable\n\n-> If count of "AAA" is more than "BBB" than than Alice wins otherwise Bob wins Why?\n\n> If count of "AAA" is less than "BBB" than Bob have more pieces to remove, and if count of both "AAA","BBB" are same(or both are zero) than on Alice will the first one to start and on her turn she couldn\'t remove a piece therefore she will be the one to lose.\n\n# Complexity\n- Time complexity: O(n), 84.69% better than Cpp online submissions\n\n- Space complexity:O(1), 79.53% better than Cpp online submissions\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string c) {\n if(c.size()==2)\n return false;\n int a=0,b=0;\n for(int i=1;i<c.size()-1;i++)\n {\n if(c[i]==\'A\' && c[i-1]==\'A\' && c[i+1]==\'A\')\n {\n a++;\n } \n else if(c[i]==\'B\' && c[i-1]==\'B\' && c[i+1]==\'B\')\n {\n b++;\n }\n }\n if(a==b || a<b)\n return false;\n else\n return true;\n }\n};\n```
2
0
['Math', 'String', 'C', 'Counting', 'C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Solution : Remove Colored Pieces if Both Neighbors are the Same Color
solution-remove-colored-pieces-if-both-n-x6u5
```class Solution {\n public boolean winnerOfGame(String c) {\n int a = 0;\n int b = 0; \n for(int i = 1; i <= c.length() - 2; i++){\n
rahul_m
NORMAL
2022-08-17T22:36:07.038890+00:00
2022-08-17T22:37:07.147855+00:00
249
false
```class Solution {\n public boolean winnerOfGame(String c) {\n int a = 0;\n int b = 0; \n for(int i = 1; i <= c.length() - 2; i++){\n if((c.charAt(i) == c.charAt(i-1)) && (c.charAt(i) == c.charAt(i+1))){\n if(c.charAt(i) == \'A\') {\n a++;\n } else {\n b++;\n }\n }\n }\n if(a>b) return true;\n return false;\n }\n}
2
0
['Math', 'Java']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
[C++] & [Python] || O(N)|| Easy to understand
c-python-on-easy-to-understand-by-ritesh-nvez
C++\n\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int l = colors.length();\n int ca=0, cb=0;\n if(l<3) return fals
RiteshKhan
NORMAL
2022-07-03T16:29:29.138926+00:00
2022-07-03T16:34:01.810896+00:00
472
false
**C++**\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int l = colors.length();\n int ca=0, cb=0;\n if(l<3) return false;\n for(int i=0; i<=l-3; ++i){\n if(colors[i]==colors[i+1] && colors[i+1]==colors[i+2]){\n if(colors[i] == \'A\') ca++;\n else cb++;\n }\n }\n return ca>cb;\n }\n};\n```\n**Python3**\n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n l = len(colors)\n ca, cb =0, 0\n if(l<3): return False\n for i in range(l-2):\n if(colors[i]==colors[i+1] and colors[i+1]==colors[i+2]):\n if(colors[i] == \'A\'): ca += 1\n else: cb += 1\n return ca>cb\n```
2
0
['C', 'Python']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
C++ (single pass)
c-single-pass-by-dakre-euyl
\n bool winnerOfGame(string colors) {\n int a = 0, b = 0, s = colors.size();\n for (int i = 0; i < s-2; ++i) {\n if (colors[i] == \'
dakre
NORMAL
2022-05-18T00:04:02.875344+00:00
2022-05-18T00:04:02.875389+00:00
154
false
```\n bool winnerOfGame(string colors) {\n int a = 0, b = 0, s = colors.size();\n for (int i = 0; i < s-2; ++i) {\n if (colors[i] == \'A\' && colors[i+1] == \'A\' && colors[i+2] == \'A\')\n a++;\n else if (colors[i] == \'B\' && colors[i+1] == \'B\' && colors[i+2] == \'B\')\n b++;\n }\n return a > b;\n }\n```
2
0
['C']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
Easy Python
easy-python-by-true-detective-pund
\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n def continuous_pieces(color):\n ans = cur = 0\n for c in colo
true-detective
NORMAL
2022-05-17T07:19:18.395318+00:00
2022-05-17T07:19:18.395349+00:00
159
false
```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n def continuous_pieces(color):\n ans = cur = 0\n for c in colors:\n if c == color:\n cur += 1\n else:\n if cur > 2: \n ans += cur - 2\n cur = 0\n if colors[-1] == color and cur > 2: ans += cur - 2\n return ans\n \n alice = continuous_pieces(\'A\')\n bob = continuous_pieces(\'B\')\n return alice > 0 and alice > bob\n```
2
0
[]
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Python 3 | Greedy
python-3-greedy-by-jose-milanes-x512
When either of them makes a move, it does not affect the other person being able to make a move in any way, so it is enough to check how many moves they can mak
Jose-Milanes
NORMAL
2022-04-11T19:20:54.110226+00:00
2022-04-11T20:52:21.582244+00:00
164
false
When either of them makes a move, it does not affect the other person being able to make a move in any way, so it is enough to check how many moves they can make. \n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n a,b = 0, 0\n for i in range(1, len(colors) - 1):\n if colors[i] == \'A\' and colors[i - 1] == \'A\' and colors[i + 1] == \'A\':\n a += 1\n if colors[i] == \'B\' and colors[i - 1] == \'B\' and colors[i + 1] == \'B\':\n b += 1\n return True if a > b else False\n```
2
0
['Greedy']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Simple C++ Solution || O(n)
simple-c-solution-on-by-purohit800-hnrk
\nclass Solution {\npublic:\n bool winnerOfGame(string colors) \n {\n int a=0,b=0;\n if(colors.size()<3)\n return false;\n
purohit800
NORMAL
2022-01-27T17:00:50.096137+00:00
2022-01-27T17:00:50.096182+00:00
110
false
```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) \n {\n int a=0,b=0;\n if(colors.size()<3)\n return false;\n for(int i=0;i<colors.size()-2;i++)\n {\n if(colors[i]==\'A\' and colors[i+1]==\'A\' and colors[i+2]==\'A\')\n a++;\n if(colors[i]==\'B\' and colors[i+1]==\'B\' and colors[i+2]==\'B\')\n b++;\n }\n return a>b;\n }\n};\n```
2
0
['C']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Count Together A's and B's || Easy
count-together-as-and-bs-easy-by-ankursh-yvy0
```\n bool winnerOfGame(string colors) {\n \n int cntA = 1 , cntB = 1;\n int totA = 0 , totB = 0;\n string s = colors ;\n \n
ankursharma6084
NORMAL
2021-10-19T06:33:35.997999+00:00
2021-10-19T06:33:35.998049+00:00
86
false
```\n bool winnerOfGame(string colors) {\n \n int cntA = 1 , cntB = 1;\n int totA = 0 , totB = 0;\n string s = colors ;\n \n for(int i=1 ; i<colors.size() ; i++ )\n {\n if(s[i] == s[i-1])\n {\n if(s[i] == \'A\') cntA++;\n else cntB++;\n }\n \n // ABBBBBBBAAA\n \n else{\n totA+= max(0 , cntA-2 ) ;\n totB+= max(0 , cntB-2 ) ;\n cntA = 1 , cntB = 1;\n\n }\n }\n \n totA+= max(0 , cntA-2 ) ;\n totB+= max(0 , cntB-2 ) ;\n cntA = 1 , cntB = 1;\n \n if(totA > totB) return 1;\n return 0;\n}
2
0
[]
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Java Simple & Easy Approach
java-simple-easy-approach-by-rohitkumars-wpjf
\nclass Solution {\n public boolean winnerOfGame(String colors) {\n \n int len=colors.length();\n \n int acount=0;\n int b
rohitkumarsingh369
NORMAL
2021-10-18T06:25:29.662286+00:00
2021-10-18T06:27:30.109514+00:00
127
false
```\nclass Solution {\n public boolean winnerOfGame(String colors) {\n \n int len=colors.length();\n \n int acount=0;\n int bcount=0;\n \n for(int i=1;i<len-1;i++){\n if(colors.charAt(i-1)==colors.charAt(i) && colors.charAt(i+1)==colors.charAt(i) )\n {\n if(colors.charAt(i)==\'A\')\n acount++;\n else\n bcount++;\n }\n }\n \n return acount>bcount;\n }\n}\n```
2
0
['Java']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
[Python3] greedy 5-line
python3-greedy-5-line-by-ye15-aqul
\n\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n diff = 0 \n for k, grp in groupby(colors): \n if k == "A": diff
ye15
NORMAL
2021-10-16T16:01:01.512243+00:00
2021-10-16T16:01:01.512276+00:00
247
false
\n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n diff = 0 \n for k, grp in groupby(colors): \n if k == "A": diff += max(0, len(list(grp)) - 2)\n else: diff -= max(0, len(list(grp)) - 2)\n return diff > 0 \n```
2
1
['Python3']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
[Java] - Easy, Compare(Count(AAA,BBB))
java-easy-comparecountaaabbb-by-pgthebig-fe6o
Idea\n-> Just count such pairs that have same neighbours!\n\nTime Complexity\n-> O(n)\n\n\nclass Solution {\n public boolean winnerOfGame(String str) {\n
pgthebigshot
NORMAL
2021-10-16T16:00:47.090380+00:00
2021-10-16T17:06:57.349928+00:00
180
false
**Idea**\n-> Just count such pairs that have same neighbours!\n\n**Time Complexity**\n-> O(n)\n\n```\nclass Solution {\n public boolean winnerOfGame(String str) {\n \n \tint i,n=str.length(),a=0,b=0;\n \tif(n<3)\n \t\treturn false;\n \tfor(i=1;i<n-1;i++)\n \t{\n \t\tif(str.charAt(i-1)==\'A\'&&str.charAt(i)==\'A\'&&str.charAt(i+1)==\'A\')\n \t\t\ta++;\n \t\tif(str.charAt(i-1)==\'B\'&&str.charAt(i)==\'B\'&&str.charAt(i+1)==\'B\')\n \t\t\tb++;\n \t}\n \treturn a>b;\n }\n}\n```\n\nIf you guys get it then I will be more **happy** if you **upvote** my solution!
2
1
['Java']
3
remove-colored-pieces-if-both-neighbors-are-the-same-color
java
java-by-aryaman123-r79j
IntuitionApproachComplexity Time complexity: Space complexity: Code
aryaman123
NORMAL
2025-03-31T17:10:03.628679+00:00
2025-03-31T17:10:03.628679+00:00
10
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public boolean winnerOfGame(String colors) { // alice can remove 'A' if both its neighbours are also 'A' // bob can remove 'B' if both its neighbours are also 'B' // cannot remove from the edge of the line // if a player cannot move on their turn then that player looses int n = colors.length(); if(n<=2) return false; int alice = 0; int bob = 0; for(int i = 1; i<n-1 ; i++){ if(colors.charAt(i-1) == colors.charAt(i) && colors.charAt(i)==colors.charAt(i+1)){ if(colors.charAt(i)=='A') alice++; else bob++; } } return alice-bob>=1; } } ```
1
0
['Java']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
eASy sOlutioN iN cPp.
easy-solution-in-cpp-by-xegl87zdze-fjmm
IntuitionApproachComplexity Time complexity:O(n) Space complexity:O(1) Code
xegl87zdzE
NORMAL
2025-03-20T15:32:29.574813+00:00
2025-03-20T15:32:29.574813+00:00
16
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 ```cpp [] class Solution { public: bool winnerOfGame(string colors) { if(colors.size() <= 2) { return false; } int alice=0,bob=0,n1=0,n2=0; for(int j=0;j<colors.size();j++) { if(colors[j] == 'A') { if(n2 >= 3) { bob=bob+(n2-2); } n2=0; n1+=1; } if(colors[j] == 'B') { if(n1 >= 3) { alice=alice+(n1-2); } n1=0; n2+=1; } } if(n1 >= 3) { alice+=(n1-2); } if(n2 >= 3) { bob+=(n2-2); } return alice > bob; } }; ```
1
0
['Math', 'String', 'Greedy', 'Game Theory', 'C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Simple & Intuitive O(n) Java Solution.
simple-intuitive-on-java-solution-by-wsh-8xo6
Intuition\nA grouping of AAA means that Alice can remove one color. So a grouping of AAAA would mean that Alice can remove 2 colors. A grouping of AAAAA would m
wsheppard9
NORMAL
2024-08-02T02:59:48.313594+00:00
2024-08-02T03:42:42.529525+00:00
8
false
# Intuition\nA grouping of AAA means that Alice can remove one color. So a grouping of AAAA would mean that Alice can remove 2 colors. A grouping of AAAAA would mean that Alice can remove 3 colors, and so on. Notice how that number keeps going up. We should keep track of it somehow! Whoever can remove the most colors, will win the game eventually. Thus if we can devise an algorithm to keep track of this number of A\'s or B\'s such that AAA would be 1 and AAAA would return 2, and so on, we can calculate if A > B, Alice wins, if A < B, Bob wins, and if A = B, Bob wins.\n\n# Approach\nCreate an algorithm that will take in two parameters ```(String colors, char target)```, where colors is the colors String given and target is either A or B. Within this algorithm, you must look for the target within your string. While iterating through the string, if the current character matches the target, you need to increment a counter. If the current character does not match the target, set the counter to 0. This simulates having to start all over if you reach a character that doesn\'t match the target. In this case, you\'d want to start counting over again. Now, if the counter at any point is greater than or equal to 3, then you will want to increment another counter aka ```result```that keeps track of the amount of letters that a player may remove.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n public boolean winnerOfGame(String colors) {\n int a = getLetterFrequency(colors, \'A\');\n int b = getLetterFrequency(colors, \'B\');\n\n if (a > b) {\n return true;\n } else if (a < b) {\n return false;\n } else {\n return false;\n }\n }\n\n private int getLetterFrequency(String colors, char target) {\n int counter = 0;\n int result = 0;\n\n for (int i = 0; i < colors.length(); i++) {\n char color = colors.charAt(i);\n\n if (color == target) {\n counter++;\n } else {\n counter = 0;\n }\n if (counter >= 3) {\n result++;\n }\n }\n return result;\n }\n}\n\n```
1
0
['Java']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Very Very Easy Java Solution
very-very-easy-java-solution-by-himanshu-s6te
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
Himanshu_Gahlot
NORMAL
2024-04-25T13:37:46.949428+00:00
2024-04-25T13:37:46.949464+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean winnerOfGame(String colors) {\n int countA=0;\n int countB=0;\n for(int i=1;i<colors.length()-1;i++){\n if(colors.charAt(i)==\'A\'&&colors.charAt(i+1)==\'A\'&&colors.charAt(i-1)==\'A\')\n countA++;\n if(colors.charAt(i)==\'B\'&&colors.charAt(i+1)==\'B\'&&colors.charAt(i-1)==\'B\')\n countB++;\n }\n if(countA>countB)\n return true;\n return false;\n }\n}\n```
1
0
['Java']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
GLBians cum here!
glbians-cum-here-by-xplicit_aman-9isd
Intuition\n1. You can remove an element if both its neighbours have the same colour as the current element, meaning all the A coloured elements between 2 A colo
xplicit_aman
NORMAL
2024-03-26T11:02:17.547837+00:00
2024-03-26T11:02:17.547871+00:00
6
false
# Intuition\n1. You can remove an element if both its neighbours have the same colour as the current element, meaning all the A coloured elements between 2 A coloured elements can be removed. (same for B)\n We use this information to calculate the total number of moves that can be made by Alice and Bob each.\n2. Alice plays first so she needs to make more moves than Bob to win the game.\n\n# Approach\n1. We calculate the total number of As in a contiguous sub-string of As before we hit the first B then add current count(A)-2 to the number of turns Alice can make. We do the same for B this time and we keep repeating till the end of string.\n2. Now, if Alice has a total number of moves more than Bobs, then she wins, else Bob wins.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int n=colors.size();\n pair<int, int> turns;\n int cnta{}, cntb{};\n for(int i{0}; i<n; i++)\n if(colors[i]==\'A\'){\n if(cntb!=0){\n turns.second+=(cntb>2)?cntb-2:0;\n cntb=0;\n }\n cnta++;\n }\n else{\n if(cnta!=0){\n turns.first+=(cnta>2)?cnta-2:0;\n cnta=0;\n }\n cntb++;\n }\n\n if(cnta!=0)\n turns.first+=(cnta>2)?cnta-2:0;\n if(cntb!=0)\n turns.second+=(cntb>2)?cntb-2:0;\n if(turns.first>turns.second) return true;\n return false;\n }\n};\n```
1
0
['C++']
1
remove-colored-pieces-if-both-neighbors-are-the-same-color
Beats 95% | Very simple sol | Time - O(n) | Space - O(1)
beats-95-very-simple-sol-time-on-space-o-7ozk
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
Atharav_s
NORMAL
2024-02-24T06:12:37.274870+00:00
2024-02-24T06:12:37.274904+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int n = colors.length();\n int alice = 0; // how many alice can remove\n int bob = 0; // how many bob can remove\n\n for(int i=1;i<n-1;i++){\n if(colors[i-1]==colors[i] && colors[i]==colors[i+1]){\n if(colors[i]==\'A\') alice++;\n else bob++;\n }\n }\n\n return alice > bob;\n }\n};\n```
1
0
['C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
✅ C++ Easy Solution || Beats 96% of Users🔥🔥🔥
c-easy-solution-beats-96-of-users-by-gau-lmyp
\n# Code\n\nclass Solution {\npublic:\n bool winnerOfGame(string c) {\n int a=0;\n int b=0;\n for(int i=1;i<c.length()-1;i++){\n
Gaurav_Tomar
NORMAL
2024-01-05T03:56:16.726042+00:00
2024-01-05T03:56:16.726087+00:00
1
false
\n# Code\n```\nclass Solution {\npublic:\n bool winnerOfGame(string c) {\n int a=0;\n int b=0;\n for(int i=1;i<c.length()-1;i++){\n if(c[i+1]==c[i] && c[i-1]==c[i] && c[i]==\'A\'){\n a++;\n }\n else if(c[i+1]==c[i] && c[i-1]==c[i] && c[i]==\'B\'){\n b++;\n }\n }\n if(a==0){\n return false;\n }\n if(a>b){\n return true;\n }\n else{\n return false;\n }\n }\n};\n```
1
0
['Game Theory', 'C++']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Python Solution using Sliding Window
python-solution-using-sliding-window-by-9cb1n
Code\n\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n a=0\n b=0\n s=""\n for i in range(len(colors)):\n
CEOSRICHARAN
NORMAL
2023-12-17T17:36:05.118294+00:00
2023-12-17T17:36:05.118327+00:00
13
false
# Code\n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n a=0\n b=0\n s=""\n for i in range(len(colors)):\n if(len(s)<3):\n s+=colors[i]\n else:\n s=s[1:]+colors[i]\n if(s==\'AAA\'):\n a+=1\n if(s==\'BBB\'):\n b+=1\n if(a>b):\n return True\n return False\n\n```
1
0
['Sliding Window', 'Python3']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Python Solution: brief explain
python-solution-brief-explain-by-s117n-bk64
Intuition\n Describe your first thoughts on how to solve this problem. \nAccording to the rules:\n 1. Alice is only allowed to remove a piece colored \'A\' if b
s117n
NORMAL
2023-12-14T12:45:36.519398+00:00
2023-12-14T12:45:36.519427+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAccording to the rules:\n `1. Alice is only allowed to remove a piece colored \'A\' if both its neighbors are also colored \'A\'. She is not allowed to remove pieces that are colored \'B\'.`\n`2. Bob is only allowed to remove a piece colored \'B\' if both its neighbors are also colored \'B\'. He is not allowed to remove pieces that are colored \'A\'.`\n`3. Alice and Bob cannot remove pieces from the edge of the line.` \nThe first and second rules force to players to pick the letter surronded by same letters. On the other words, at least middle letter of AAA or BBB can be choosed. \nThe third one do not allow to pick the boundry string. This means AA or BB in the edge will not be considerd. \nThe only option is to choose a middle letter in string AAA or BBB. It can also be AAAA or BBBB and so on. Therefore,the question should be equal to find a substring that length >=3. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFind the substring length that should be larger than 2. \n\n\n# Code\n```\nclass Solution(object):\n def winnerOfGame(self, colors):\n """\n :type colors: str\n :rtype: bool\n """\n ## find substring in colors, length >=3\n A = colors.split(\'B\')\n B = colors.split(\'A\')\n ## got the number of A/B each substring can pick \n lena = [len(i)-2 for i in A if len(i)>=3] \n lenb = [len(j)-2 for j in B if len(j)>=3]\n # sum the total steps \n goA = sum(lena)\n goB = sum(lenb)\n # alice first,so the steps of alice should be larger than bob\n if goA > goB:\n return True\n else:\n return False \n \n```
1
0
['Python']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Intuitive Python Solution (Tc: O(n) Sc: O(1))
intuitive-python-solution-tc-on-sc-o1-by-vnee
Intuition\nSince the game is turn-based, whoever has the greatest number of matching sequences will win the game. Therefore, you only need to iterate through th
ccostello97
NORMAL
2023-12-05T01:47:29.454981+00:00
2023-12-05T01:47:29.455010+00:00
4
false
# Intuition\nSince the game is turn-based, whoever has the greatest number of matching sequences will win the game. Therefore, you only need to iterate through the loop once to determine who has the most matching sequences.\n\n# Approach\nWe iterate through the list once, starting from the second piece and stopping at the second-to-last piece (because these are the only pieces that can be extracted). Whenever we come upon "AAA", we increment Alice\'s counter, and whenever we happen upon "BBB", we increment Bob\'s counter. Finally, we compare Alice\'s count with Bob\'s count. If aliceWins > bobWins, Alice wins the game, so we return the result of that comparison directly.\n\n# Complexity\n- Time complexity:\nO(n) because only iterating through the loop once\n\n- Space complexity:\nO(1) because memory remains constant\n\n# Code\n```\nclass Solution(object):\n def winnerOfGame(self, colors):\n aliceWins, bobWins = 0, 0\n for i in range(1, len(colors) - 1):\n consecutiveColors = colors[i-1:i+2]\n if consecutiveColors == "AAA":\n aliceWins += 1\n elif consecutiveColors == "BBB":\n bobWins += 1\n return aliceWins > bobWins\n \n```
1
0
['Python']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Fast way to solve the problem with O(n) time, O(1) space
fast-way-to-solve-the-problem-with-on-ti-mq4b
Approach\njust imagine of 2 pointer on the left i-1 and right i+1 and sum byte of character to be 195 or 198 and then count it if countA > countB alice should b
user9994g
NORMAL
2023-10-18T09:09:47.615003+00:00
2023-10-18T09:09:47.615024+00:00
3
false
# Approach\njust imagine of 2 pointer on the left i-1 and right i+1 and sum byte of character to be 195 or 198 and then count it if countA > countB alice should be won\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```\nconst A byte = 195 // ascii 65*3\nconst B byte = 198 // ascii 66*3\n\nfunc winnerOfGame(colors string) bool {\n countA := 0\n countB := 0\n\n for i := 1; i < len(colors); i++ {\n if i+1 > len(colors)-1 {\n break\n }\n added := colors[i-1]+colors[i]+colors[i+1]\n switch added {\n case 195: countA++\n case 198: countB++\n default: continue\n }\n }\n\n return countA > countB\n}\n```\n\n![image.png](https://assets.leetcode.com/users/images/ba0004fa-7c0c-4866-bd51-7c2218bb4116_1697620122.569614.png)\n
1
0
['Go']
0
remove-colored-pieces-if-both-neighbors-are-the-same-color
Remove Colored Pieces if Both Neighbors are the Same Color
remove-colored-pieces-if-both-neighbors-84b1i
Intuition\nIf Alice has a higher possible turn count than Bob, Alice is the winner. A possible turn is counted if the same letter occurs consecutively 3 times o
minie2000
NORMAL
2023-10-06T05:44:36.052393+00:00
2023-10-06T05:44:36.052421+00:00
10
false
# Intuition\nIf Alice has a higher possible turn count than Bob, Alice is the winner. A possible turn is counted if the same letter occurs consecutively 3 times or more.\n\n# Approach\nI have declared some variables to check if the same letter occurs consecutively three times or more. If the consecutive count is 3 or greater, the possible turn count increases.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\npublic class Solution {\n public bool WinnerOfGame(string colors) {\n int n = colors.Length;\n int aliceTurn = 0;\n int bobTurn = 0;\n int countA = 0;\n int countB = 0;\n\n for (int i = 0; i < n; i++) {\n if (colors[i] == \'A\') {\n countA++;\n countB = 0;\n\n if (countA >= 3) {\n aliceTurn++;\n }\n } else if (colors[i] == \'B\') {\n countB++;\n countA = 0;\n\n if (countB >= 3) {\n bobTurn++;\n }\n }\n }\n\n return aliceTurn > bobTurn;\n }\n}\n\n```
1
0
['C#']
0
detonate-the-maximum-bombs
[Python] Simple dfs, explained
python-simple-dfs-explained-by-dbabichev-9iy3
In fact, this is graph proglem, starting with bomb, we need to traverse all bombs we can detonate and so on. Problem constraints allow us to just use bruteforce
dbabichev
NORMAL
2021-12-11T16:01:58.852955+00:00
2021-12-11T16:01:58.852979+00:00
18,529
false
In fact, this is graph proglem, starting with bomb, we need to traverse all bombs we can detonate and so on. Problem constraints allow us to just use bruteforce.\n\n#### Complexity\nTime complexity is `O(n^3)`, because we start from `n` bombs and we can have upto `O(n^2)` edges.\n\n#### Code\n```python\nclass Solution:\n def maximumDetonation(self, B):\n n, ans, G = len(B), 0, defaultdict(list)\n \n for i in range(n):\n for j in range(n):\n if i == j: continue\n if B[i][2]**2 >= (B[i][0] - B[j][0])**2 + (B[i][1] - B[j][1])**2:\n G[i] += [j]\n \n \n def dfs(node, visited):\n for child in G[node]:\n if child not in visited:\n visited.add(child)\n dfs(child, visited)\n\n for i in range(n):\n visited = set([i])\n dfs(i, visited)\n ans = max(ans, len(visited))\n \n return ans\n```\n\n#### Remark\nThere is also `O(n^2)` solution: let us keep for each node set of nodes we can reach from this node: than we can recalculate it with usual dfs.\n\nIf you have any question, feel free to ask. If you like the explanations, please **Upvote!**
100
4
['Depth-First Search']
18
detonate-the-maximum-bombs
BFS (or DFS)
bfs-or-dfs-by-votrubac-2zkb
We can represent bombs using a directed graph - when a bomb i can detonate bomb j, there is an edge from i to j. Note that the opposite may not be true.\n\nWe g
votrubac
NORMAL
2021-12-11T16:02:54.141479+00:00
2021-12-11T18:50:39.108722+00:00
20,784
false
We can represent bombs using a *directed* graph - when a bomb `i` can detonate bomb `j`, there is an edge from `i` to `j`. Note that the opposite may not be true.\n\nWe generate this graph (`al`), and, starting from each node, we run BFS (or DFS) and find out how many nodes we can reach.\n\n#### DFS\nUsing a bitset boosted the runtime to 28 ms.\n\n**C++**\n```cpp\nint dfs(int i, vector<vector<int>> &al, bitset<100> &detonated) {\n if (!detonated[i]) {\n detonated[i] = true;\n for (int j : al[i])\n dfs(j, al, detonated);\n }\n return detonated.count();\n}\nint maximumDetonation(vector<vector<int>>& bs) {\n int res = 0, sz = bs.size();\n vector<vector<int>> al(bs.size());\n for (int i = 0; i < sz; ++i) {\n long long x = bs[i][0], y = bs[i][1], r2 = (long long)bs[i][2] * bs[i][2];\n for (int j = 0; j < bs.size(); ++j)\n if ((x - bs[j][0]) * (x - bs[j][0]) + (y - bs[j][1]) * (y - bs[j][1]) <= r2)\n al[i].push_back(j);\n }\n for (int i = 0; i < sz && res < sz; ++i)\n res = max(dfs(i, al, bitset<100>() = {}), res);\n return res;\n}\n```\n\n#### BFS\n**C++**\n```cpp\nint maximumDetonation(vector<vector<int>>& bs) {\n int res = 0, sz = bs.size();\n vector<vector<int>> al(bs.size());\n for (int i = 0; i < sz; ++i) {\n long long x = bs[i][0], y = bs[i][1], r2 = (long long)bs[i][2] * bs[i][2];\n for (int j = 0; j < bs.size(); ++j)\n if ((x - bs[j][0]) * (x - bs[j][0]) + (y - bs[j][1]) * (y - bs[j][1]) <= r2)\n al[i].push_back(j);\n }\n for (int i = 0; i < sz && res < sz; ++i) {\n vector<int> q{i};\n unordered_set<int> detonated{i};\n while (!q.empty()) {\n vector<int> q1;\n for (int j : q)\n for (int k : al[j])\n if (detonated.insert(k).second)\n q1.push_back(k);\n swap(q, q1);\n }\n res = max((int)detonated.size(), res);\n }\n return res;\n}\n```
70
1
[]
18
detonate-the-maximum-bombs
C++ || EASY TO UNDERSTAND || using basic DFS
c-easy-to-understand-using-basic-dfs-by-0lvlj
\n\nclass Solution {\n#define ll long long int\n public:\n void dfs(vector<vector<int>> &graph,vector<bool> &visited,int &c,int &i)\n {\n visite
aarindey
NORMAL
2021-12-12T01:43:05.717149+00:00
2021-12-12T01:43:05.717204+00:00
11,812
false
```\n\nclass Solution {\n#define ll long long int\n public:\n void dfs(vector<vector<int>> &graph,vector<bool> &visited,int &c,int &i)\n {\n visited[i]=true;\n c++;\n for(int j=0;j<graph[i].size();j++)\n {\n if(!visited[graph[i][j]])\n dfs(graph,visited,c,graph[i][j]); \n }\n }\n int maximumDetonation(vector<vector<int>>& bombs) {\n\n int n=bombs.size();\n vector<vector<int> > graph(n);\n for(int i=0;i<n;i++)\n {\n ll x1,y1,r1;\n x1=bombs[i][0];\n y1=bombs[i][1];\n r1=bombs[i][2];\n for(int j=0;j<n;j++)\n {\n if(i!=j)\n {\n ll x2,y2,r2;\n x2=abs(x1-bombs[j][0]);\n y2=abs(y1-bombs[j][1]);\n if(x2*x2+y2*y2<=r1*r1)\n {\n graph[i].push_back(j);\n }\n }\n }\n }\n int ans=INT_MIN;\n for(int i=0;i<n;i++)\n {\n int c=0;\n vector<bool> visited(n,false);\n dfs(graph,visited,c,i);\n ans=max(ans,c);\n }\n return ans;\n }\n};\n```\n**Please upvote to motivate me in my quest of documenting all leetcode solutions(to help the community). HAPPY CODING:)\nAny suggestions and improvements are always welcome**
68
1
['Depth-First Search', 'Graph']
9
detonate-the-maximum-bombs
Neat Code Java DFS
neat-code-java-dfs-by-vegetablebirds-14a7
```\n public int maximumDetonation(int[][] bombs) {\n int n = bombs.length, ans = 0;\n for (int i = 0; i < n; i++) {\n ans = Math.max(a
Vegetablebirds
NORMAL
2021-12-11T23:01:27.171543+00:00
2023-07-18T13:01:26.831635+00:00
10,137
false
```\n public int maximumDetonation(int[][] bombs) {\n int n = bombs.length, ans = 0;\n for (int i = 0; i < n; i++) {\n ans = Math.max(ans, dfs(i, new boolean[n], bombs));\n }\n return ans;\n }\n\n private int dfs(int idx, boolean[] v, int[][] bombs) {\n int count = 1;\n v[idx] = true;\n int n = bombs.length;\n for (int i = 0; i < n; i++) {\n if (!v[i] && inRange(bombs[idx], bombs[i])) {\n count += dfs(i, v, bombs);\n }\n }\n return count;\n }\n\n private boolean inRange(int[] a, int[] b) {\n long dx = a[0] - b[0], dy = a[1] - b[1], r = a[2];\n return dx * dx + dy * dy <= r * r;\n }\n
51
0
['Depth-First Search', 'Java']
12
detonate-the-maximum-bombs
Wrong test cases?
wrong-test-cases-by-trickster-oawr
For the input\n\n[[54,95,4],[99,46,3],[29,21,3],[96,72,8],[49,43,3],[11,20,3],[2,57,1],[69,51,7],[97,1,10],[85,45,2],[38,47,1],[83,75,3],[65,59,3],[33,4,1],[32,
trickster_
NORMAL
2021-12-11T16:08:42.263280+00:00
2021-12-11T16:08:42.263308+00:00
3,747
false
For the input\n```\n[[54,95,4],[99,46,3],[29,21,3],[96,72,8],[49,43,3],[11,20,3],[2,57,1],[69,51,7],[97,1,10],[85,45,2],[38,47,1],[83,75,3],[65,59,3],[33,4,1],[32,10,2],[20,97,8],[35,37,3]]\n```\nConsider the points at index 7 and 12\n69, 51, 7\n65, 59, 3\n\nGraphing them,\n![image](https://assets.leetcode.com/users/images/ba9fa35f-c318-41cf-9bc4-0fc2a94d2af8_1639238833.236306.png)\n\nThe answer should be at least 2, however the judge tells 1.\nAm I doing something wrong here?\n
43
5
[]
14
detonate-the-maximum-bombs
Java | BFS & DFS | With Comments | Easy
java-bfs-dfs-with-comments-easy-by-omars-dyru
The main idea here is to take each bomb and check the number of bombs in its range. \n\nBFS: \n\n\n public int maximumDetonation(int[][] bombs) {\n in
omars_leet
NORMAL
2022-03-30T13:52:00.398685+00:00
2022-04-02T21:18:36.299163+00:00
4,978
false
The main idea here is to take each bomb and check the number of bombs in its range. \n\n**BFS**: \n\n```\n public int maximumDetonation(int[][] bombs) {\n int max = 0;\n //iterate through each bomb and keep track of max\n for(int i = 0; i<bombs.length; i++){\n max = Math.max(max, getMaxBFS(bombs, i)); \n }\n return max;\n }\n \n private int getMaxBFS(int[][] bombs, int index){\n Queue<Integer> queue = new LinkedList<>();\n boolean[] seen = new boolean[bombs.length];\n \n seen[index] = true;\n queue.offer(index);\n \n int count = 1; // start from 1 since the first added bomb can detonate itself\n \n while(!queue.isEmpty()){\n int currBomb = queue.poll();\n for(int j = 0; j<bombs.length; j++){ //search for bombs to detonate\n if(!seen[j] && isInRange(bombs[currBomb], bombs[j])){\n seen[j] = true;\n count++;\n queue.offer(j);\n }\n }\n }\n \n return count;\n }\n \n //use the distance between two points formula\n //then check if curr bomb radius is greater than the distance; meaning we can detonate the second bombs\n private boolean isInRange(int[] point1, int[] point2) {\n long dx = point1[0] - point2[0], dy = point1[1] - point2[1], radius = point1[2];\n long distance = dx * dx + dy * dy;\n return distance <= radius * radius;\n }\n```\n\n**DFS**: \n\n```\n public int maximumDetonation(int[][] bombs) {\n int max = 0;\n for (int i = 0; i < bombs.length; i++) {\n max = Math.max(max, getMaxDFS(i, bombs, new boolean[bombs.length]));\n }\n return max;\n }\n\n private int getMaxDFS(int index, int[][] bombs, boolean[] seen) {\n int count = 1;\n seen[index] = true;\n\n for (int i = 0; i < bombs.length; i++) {\n if (!seen[i] && isInRange(bombs[index], bombs[i])) {\n count += getMaxDFS(i, bombs, seen);\n }\n }\n\n return count;\n }\n\n private boolean isInRange(int[] point1, int[] point2) {\n long dx = point1[0] - point2[0], dy = point1[1] - point2[1], radius = point1[2];\n long distance = dx * dx + dy * dy;\n return distance <= radius * radius;\n }\n```
29
0
['Depth-First Search', 'Breadth-First Search', 'Java']
4
detonate-the-maximum-bombs
Intuition Explained | Can simple DFS be further optimized?
intuition-explained-can-simple-dfs-be-fu-dcl3
NOTE: One Bomb can detonate other if and only if the other bomb lies within the area covered by the Bomb.\n\n\n\n\n\n\n\n\nclass Solution {\npublic:\n double
27aryanraj
NORMAL
2021-12-13T15:20:49.734223+00:00
2023-04-14T20:24:07.933749+00:00
2,317
false
**NOTE: One Bomb can detonate other if and only if the other bomb lies within the area covered by the Bomb.**\n\n![image](https://assets.leetcode.com/users/images/f3110632-4cc7-4461-917b-489c8bc8b2e9_1639405880.1813633.png)\n\n![image](https://assets.leetcode.com/users/images/094a740b-d884-49af-be24-12b298167b9c_1639407042.709457.png)\n\n![image](https://assets.leetcode.com/users/images/a6f31a54-89db-401b-a12a-8f0326056bf4_1639408158.857844.png)\n\n```\nclass Solution {\npublic:\n double calcDis(int& x1, int& y1, int& x2, int& y2){\n \n long double dis = sqrtl(1LL * (x1-x2)*(x1-x2) + 1LL * (y1-y2)*(y1-y2));\n \n return dis;\n }\n \n void dfs(int node, vector<int>& visited,int& thisPathBombs, vector<int> canDetonate[]){\n \n visited[node] = 1;\n thisPathBombs++;\n \n for(int i=0;i<canDetonate[node].size();i++){\n \n int cnode = canDetonate[node][i];\n \n if(visited[cnode] == -1){\n dfs(cnode,visited,thisPathBombs,canDetonate);\n }\n }\n }\n \n int maximumDetonation(vector<vector<int>>& bombs) {\n \n int n = bombs.size();\n \n vector<int> canDetonate[n];\n \n int mxBombs = 0;\n \n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n double dis = calcDis(bombs[i][0],bombs[i][1],bombs[j][0],bombs[j][1]);\n double d1 = bombs[i][2] * 1.0;\n double d2 = bombs[j][2] * 1.0;\n \n if(dis <= d1){\n canDetonate[i].push_back(j);\n }\n \n if(dis <= d2){\n canDetonate[j].push_back(i);\n }\n }\n }\n \n for(int i=0;i<n;i++) {\n int thisPathBombs = 0;\n vector<int> visited(n,-1);\n dfs(i,visited,thisPathBombs,canDetonate);\n mxBombs = max(mxBombs, thisPathBombs);\n }\n \n return mxBombs;\n }\n};\n```\n\n**Here we are running dfs for every node for multiple times.**\n\n![image](https://assets.leetcode.com/users/images/15b06225-569e-4f44-aca3-eb6d5bf70a51_1639408208.1803577.png)\n\n![image](https://assets.leetcode.com/users/images/3598d97d-4c55-4949-b913-7c1bac856242_1639408657.9182005.png)\n\n\n\n\n
28
0
['Depth-First Search', 'Graph', 'C++']
6
detonate-the-maximum-bombs
Intuition Explained || Graph, DFS based approach || C++ Clean Code
intuition-explained-graph-dfs-based-appr-ld74
Intuition :\n\n Idea here is to first create a graph, such that there is a edge between two bombs i and j,\n\n\t if when we detonate ith bomb, then jth bomb lie
i_quasar
NORMAL
2021-12-31T12:36:31.680063+00:00
2021-12-31T12:38:17.130913+00:00
2,421
false
**Intuition :**\n\n* Idea here is to first create a graph, such that there is a edge between two bombs `i` and `j`,\n\n\t* if when we detonate `ith` bomb, then `jth bomb` lies within its **proximity** (as given in problem stmt),\n\t* i.e iff **`distance between centers <= radius of ith bomb`**\n* To create graph, simply we need to loop over `bombs` list, and then for each `bomb i`, \n\t* we need to check if a `bomb j` lies withing its **proximity**. \n\t* In this way we will create `deto_adj`, where `deto_adj[i]` is list of all bombs that lie in its proximity\n\n\t\t\tEx : say we have i = 2, n = 4. Also, say j = 0, 3 are nodes that lie within its proximity\n\t\t\t\n\t\t\t# 2 -> 0, 3\n\t\t\t\n\t\t\tThen, deto_adj[i] = deto_adj[2] = {0, 3} \n\t\t\t\n\t\t\tNote: This is a directed edge. \n\t\t\t\n\t\t\t\n* So, once we have our graph [adjacency list], next for each bomb in `bombs` list, simply do a **DFS (or BFS)**, and \n\t* ***count the number of bombs (nodes) it can visit.***\n* In then end we need to return the maximum count among all the bombs.\n\n------------------\n# Code : DFS Approach\n\n```\nclass Solution {\npublic:\n \n\t// Check if (x2, y2) lie within the proximity of (x1, y1)\n bool check(long long x1, long long y1, long long x2, long long y2, long long d) {\n long long x = (x1-x2) * (x1-x2);\n long long y = (y1-y2) * (y1-y2);\n \n return (x + y <= d * d);\n }\n \n\t// DFS to detonate "node" , and count number of other nodes \n\t// that can be detonated (visited) from currernt node.\n int detonate(vector<vector<int>>& adj, vector<bool>& vis, int node, int n) {\n \n int count = 1;\n vis[node] = true;\n \n for(auto& adjnode : adj[node]) {\n if(!vis[adjnode]) {\n count += detonate(adj, vis, adjnode, n);\n }\n }\n \n return count;\n }\n \n int maximumDetonation(vector<vector<int>>& bombs) {\n \n int n = bombs.size();\n \n int maxBombs = 0;\n \n\t\t// Adjacency list to store all edges for nodes [0, n-1]\n\t\t// i.e all bombs that lie within proximity of node\n vector<vector<int>> deto_adj(n);\n \n\t\t// Create graph by connecting directed edges\n\t\t// Between ith and jth node\n for(int i=0; i<n; i++) {\n for(int j=0; j<n; j++) {\n if(i != j && check(bombs[i][0], bombs[i][1], bombs[j][0], bombs[j][1], bombs[i][2])) {\n deto_adj[i].push_back(j);\n } \n }\n }\n \n\t\t// For each bomb, do simple DFS (detonate)\n\t\t// And get count of nodes that can be visited from current node\t\t\n for(int i=0; i<n; i++) {\n vector<bool> vis(n, false);\n \n\t\t\t// Also update maximum count\n maxBombs = max(maxBombs, detonate(deto_adj, vis, i, n));\n }\n \n return maxBombs;\n }\n};\n```\n\nNote: Instead of DFS, you can also use BFS. Both approach is correct.\n\n------------------\n\n**Complexity :** \n\n* Time : `O(N * N)` , N is number of bombs\n\t* To create `deto_adj` \n\t* And then for each bomb node, perform DFS\n\n* Space : `~ O(N * N)`, to create adjacency list\n\n***If you find this helpful, do give it a like : )***
22
0
['Math', 'Depth-First Search', 'Graph', 'Geometry']
3
detonate-the-maximum-bombs
Python BFS/DFS and why union-find is not the solution.
python-bfsdfs-and-why-union-find-is-not-mlvrw
Intuition\n Describe your first thoughts on how to solve this problem. \nMy initial intuition was union-find because it seems to find out the maximum RANK of th
lhy332
NORMAL
2022-11-26T21:55:49.325047+00:00
2022-11-26T21:55:49.325087+00:00
2,600
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy initial intuition was union-find because it seems to find out the maximum RANK of the largest group. After a few trial and error, I figured out that union-find is only for undirected graph. So, I decided to solve this problem with typical BFS, DFS, DFS-Recursive approach. \n\n[Example]\nthere are three points\npoint 1 is located at x=2 with radius 5\npoint 2 is located at x=5 with radius 1\npoint 3 is located at x=10 with radius 6\n\nunion-find approach will build those three points as a graph. (max rank = 3)\nbut, in this scenario, the max value is 2 because the point 2 cannot detonate any bomb.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n0. Building adjacency list\n1. BFS with deque\n2. DFS with stack\n3. DFS with recursion\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(V + E)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(V)\n# Code\n```\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n\n def is_connected(a,b):\n x1, y1, r1 = bombs[a]\n x2, y2, r2 = bombs[b]\n dist = math.sqrt((x1-x2)**2 + (y1-y2)**2)\n return dist <= r1\n\n\n conn = collections.defaultdict(list)\n for i in range(len(bombs)):\n for j in range(len(bombs)):\n if i != j:\n if is_connected(i,j):\n conn[i].append(j)\n\n # 1. BFS\n # q = collections.deque()\n # maxCount = float(\'-inf\')\n\n # for node in range(len(bombs)):\n # if conn[node]:\n # q.append(node)\n # visited = set()\n # visited.add(node)\n # count = 0\n # while q:\n # curr = q.popleft()\n # count+=1\n # maxCount = max(maxCount, count)\n # for child in conn[curr]:\n # if child not in visited:\n # visited.add(child)\n # q.append(child)\n\n # return maxCount if maxCount != float(\'-inf\') else 1\n\n\n # 2. DFS\n\n # stack = []\n # maxCount = float(\'-inf\')\n\n # for node in range(len(bombs)):\n # if conn[node]:\n # visited = set()\n # stack.append(node)\n # visited.add(node)\n # count = 0\n # while stack:\n\n # curr = stack.pop()\n # count+=1\n # maxCount = max(maxCount, count)\n\n # for child in conn[curr]:\n # if child not in visited:\n # visited.add(child)\n # stack.append(child)\n # return maxCount if maxCount != float(\'-inf\') else 1\n\n\n # 3. DFS recursive \n \n def dfs(node):\n\n if node in visited:\n return 0\n\n visited.add(node)\n \n ans = 1\n\n if node in conn:\n for child in conn[node]:\n if child in visited:\n continue\n ans += dfs(child)\n \n return ans \n\n maxCount = 1\n for node in conn:\n visited = set()\n maxCount = max(maxCount, dfs(node))\n return maxCount\n```
17
0
['Python3']
5
detonate-the-maximum-bombs
A similar question asked in my google phone interview. (read for more)
a-similar-question-asked-in-my-google-ph-8xpl
Solving this one saved me in my google phone interview. I\'ve put the details of the interview here:\nhttps://freezefrancis.medium.com/google-phone-interview-ex
freeze_francis
NORMAL
2022-10-13T10:50:27.460569+00:00
2022-10-13T10:50:27.460617+00:00
2,073
false
Solving this one saved me in my google phone interview. I\'ve put the details of the interview here:\nhttps://freezefrancis.medium.com/google-phone-interview-experience-a75c2d0e0080
17
0
['Breadth-First Search']
2
detonate-the-maximum-bombs
C++ | Simple BFS [ Faster than 100% ]
c-simple-bfs-faster-than-100-by-priyansh-tukp
CODE\n\nclass Solution {\npublic:\n \n int maximumDetonation(vector<vector<int>>& bombs) {\n ios::sync_with_stdio(false); cin.tie(NULL);\n\t\t\n
Priyansh_34
NORMAL
2021-12-11T19:35:31.374371+00:00
2021-12-11T19:35:31.374403+00:00
2,951
false
**CODE**\n```\nclass Solution {\npublic:\n \n int maximumDetonation(vector<vector<int>>& bombs) {\n ios::sync_with_stdio(false); cin.tie(NULL);\n\t\t\n const int n = bombs.size();\n\t\t\n vector<vector<int>>v(n);\n \n for(int i = 0; i < n; i++) {\n long long r = (long long)bombs[i][2] * bombs[i][2];\n for(int j = 0; j < n; j++) {\n if(i != j){\n if((long long)((long long)bombs[i][0]-bombs[j][0]) * ((long long)bombs[i][0]-bombs[j][0])+(long long)(bombs[i][1]-bombs[j][1]) * ((long long)bombs[i][1]-bombs[j][1]) <= r){\n v[i].push_back(j);\n }\n }\n }\n }\n \n int ans = 1;\n // try each bomb and choose that which contributes maximum detonation.\n for(int i = 0; i < n; i++){\n vector<bool>vis(n, 0);\n int mx = 0;\n \n\t\t\tqueue<int>q;\n q.push(i);\n\t\t\t\n while(!q.empty()) {\n int s = q.size();\n for(int i = 0; i < s; i++) {\n int x = q.front();\n q.pop();\n vis[x] = 1;\n mx++;\n for(auto p : v[x]) {\n if(!vis[p]) {\n q.push(p);\n vis[p] = 1;\n }\n }\n }\n }\n ans = max(ans, mx);\n }\n \n return ans;\n }\n};\n```\n**Useful Problem link**\nhttps://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/\n\n**Do Upvote if you like the solution**
17
0
['Breadth-First Search']
2
detonate-the-maximum-bombs
C++ | DFS | Intuition and Code Explained
c-dfs-intuition-and-code-explained-by-ni-wjlu
Explanation\nThe intuition is to keep checking the bombs we can detonate if we start from the i-th bomb. The conditions for detonation are:\n1. The bomb shouldn
nidhiii_
NORMAL
2022-02-25T17:15:29.665537+00:00
2022-02-25T17:16:54.893970+00:00
1,967
false
### Explanation\nThe intuition is to keep checking the bombs we can detonate if we start from the i-th bomb. The conditions for detonation are:\n1. The bomb shouldn\'t be visited before (Except if that is the starting point).\n2. The distance between two points should be less than radius of the previous bomb, i.e, (x1-x2) * (y1-y2) <= r * r \n\nI have kept a visited array for every bomb and ans stores the maximum count. \n\n\n\n**Please upvote if this post helped you!** If you have any queries, you can comment below. I would be happy to help!\n\n### Code\n```\nclass Solution {\npublic:\n bool check(long long x1,long long x2, long long y1,long long y2,long long r)\n {\n long long x=(x1-x2)*(x1-x2), y=(y1-y2)*(y1-y2); \n return x+y<=r*r; //using the distance formula\n }\n \n void help(vector<vector<int>>& bombs,vector<bool>& vis,int j, int& count){\n if(vis[j])return; //if we have already detonated this bomb \n \n count++;\n vis[j]=true;\n int x1=bombs[j][0], y1=bombs[j][1], r=bombs[j][2];\n \n for(int i=0;i<bombs.size();i++){\n int x2=bombs[i][0], y2=bombs[i][1];\n if(!vis[i] && check(x1,x2,y1,y2,r)) //check if this bomb can be detonated using the previous bomb\n help(bombs,vis,i,count);\n }\n }\n \n int maximumDetonation(vector<vector<int>>& bombs) {\n int n=bombs.size();\n int ans=INT_MIN;\n \n for(int i=0;i<n;i++){\n int count=0; \n vector<bool>visited(n,false); // a visted array to keep track of the bombs already reached in the current sequence\n help(bombs,visited,i,count);\n ans=max(ans,count);\n }\n return ans;\n }\n};\n```
12
1
['Depth-First Search', 'C++']
2
detonate-the-maximum-bombs
✅ Explained - Simple and Clear Python3 Code✅
explained-simple-and-clear-python3-code-44c7q
Intuition\nThe given problem involves determining the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb. The bombs are
moazmar
NORMAL
2023-06-10T00:35:33.783952+00:00
2023-06-10T00:35:33.783990+00:00
1,264
false
# Intuition\nThe given problem involves determining the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb. The bombs are represented as a list of 2D integer arrays, where each array contains the X-coordinate, Y-coordinate, and radius of a bomb.\n\n\n# Approach\nTo solve this problem, the provided solution uses a depth-first search (DFS) approach. It first initializes an empty list called "connected" to store the connections between the bombs. Each index in the "connected" list represents a bomb, and the corresponding value is a list of indices of other bombs that can be detonated if the bomb at that index is detonated.\n\nNext, the solution iterates through each bomb and checks its range against the ranges of other bombs. If the range of the current bomb overlaps with the range of another bomb, it adds the index of the other bomb to the "connected" list for the current bomb.\n\nAfter creating the "connected" list, the solution initializes an empty list called "res" to store the results. It also initializes an empty list called "visited" to keep track of the bombs that have been visited during the DFS.\n\nThen, for each bomb, the solution performs a DFS starting from that bomb\'s index. During the DFS, it visits all the connected bombs and adds them to the "visited" list. After completing the DFS, it appends the length of the "visited" list to the "res" list.\n\nFinally, the solution returns the maximum value in the "res" list, which represents the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb.\n\n# Complexity\n- Time complexity:\nThe time complexity of this solution depends on the number of bombs, denoted as "n". The creation of the "connected" list takes O(n^2) time since it involves comparing each bomb\'s range with the ranges of other bombs. The DFS step is performed for each bomb, resulting in a time complexity of O(n^2) as well. Therefore, the overall time complexity is O(n^2).\n\n\n- Space complexity:\nThe space complexity of this solution is O(n^2) since the "connected" list stores connections for each bomb. Additionally, the "res" list and the "visited" list can each store up to n elements. Therefore, the overall space complexity is O(n^2).\n\n\n# Code\n```\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n n=len(bombs)\n connected=[ [] for i in range(n)]\n\n for i in range(n):\n sm=[]\n for j in range(n):\n if j!=i:\n xi, yi, ri = bombs[i]\n xj, yj, _ = bombs[j]\n if ri ** 2 >= (xi - xj) ** 2 + (yi - yj) ** 2:\n sm.append(j)\n connected[i]=sm\n \n res=[]\n\n visited=[]\n def dfs(i:int):\n\n if i not in visited:\n visited.append(i)\n for j in connected[i]:\n dfs(j)\n \n\n for i in range(n):\n visited.append(i)\n for j in connected[i]:\n dfs(j)\n res.append(len(visited))\n visited.clear()\n\n return max(res)\n \n \n```
11
0
['Python3']
0
detonate-the-maximum-bombs
Easy C++ Solution
easy-c-solution-by-am14-3t3t
Intuition\n Describe your first thoughts on how to solve this problem. \nIn this problem, we are given a list of bombs represented by their coordinates (x and y
am14
NORMAL
2023-06-02T05:01:59.075880+00:00
2023-06-02T10:56:54.906441+00:00
4,212
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn this problem, we are given a list of bombs represented by their coordinates (x and y) and the explosion radius. The task is to determine the maximum number of bombs that can be detonated by starting with any bomb and detonating all other bombs within its explosion range.\n\nImagine each bomb as a node in a graph. If two bombs are within range of each other, we can consider an edge between the corresponding nodes. The objective is to find the connected component with the maximum number of nodes, as it represents the maximum detonation possible.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo solve this problem, we can follow these steps:\n\n1. Initialize an adjacency list to represent the connections between bombs.\n2. Iterate over each bomb and calculate the squared explosion radius (r).\n3. Compare the squared Euclidean distance between each pair of bombs. If it is less than or equal to r, add an edge between them in the adjacency list.\n4. Initialize a variable to keep track of the maximum detonation count (ans).\n5. For each bomb, perform a BFS starting from that bomb to find the number of bombs that can be detonated.\n6. Maintain a queue and a visited array during the BFS.\n7. Start BFS from the current bomb by adding it to the queue and marking it as visited.\n8. While the queue is not empty, process the front element, increment the detonation count, and visit its adjacent bombs if they haven\'t been visited before.\n9. Update the maximum detonation count if the current count is greater.\n10. Repeat steps 5-9 for each bomb.\n11. Return the maximum detonation count as the result.\n\nBy representing the bombs as nodes in a graph and performing a BFS traversal, we can identify the connected component with the maximum number of nodes, which corresponds to the maximum detonation count.\n\n\n\n# Complexity\n- Time complexity: O(N^3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maximumDetonation(vector<vector<int>>& bombs) \n {\n const int n = bombs.size();\n vector<vector<int>> v(n);\n\n for (int i = 0; i < n; i++) \n {\n long long r = (long long) bombs[i][2] * bombs[i][2];\n for (int j = 0; j < n; j++) \n {\n if (i != j) \n {\n if ((long long) ((long long) bombs[i][0] - bombs[j][0]) * ((long long) bombs[i][0] - bombs[j][0]) + \n (long long) (bombs[i][1] - bombs[j][1]) * ((long long) bombs[i][1] - bombs[j][1]) <= r) \n {\n v[i].push_back(j);\n }\n }\n }\n }\n\n int ans = 1;\n for (int i = 0; i < n; i++) \n {\n vector<bool> vis(n, false);\n int mx = 0;\n queue<int> q;\n q.push(i);\n\n while (!q.empty()) \n {\n int s = q.size();\n for (int j = 0; j < s; j++) \n {\n int x = q.front();\n q.pop();\n vis[x] = true;\n mx++;\n for (auto p : v[x]) \n {\n if (!vis[p]) {\n q.push(p);\n vis[p] = true;\n }\n }\n }\n }\n ans = max(ans, mx);\n }\n\n return ans;\n }\n};\n\n```
11
0
['Breadth-First Search', 'C++']
2
detonate-the-maximum-bombs
Python | BFS / DFS, start with every point | explanation
python-bfs-dfs-start-with-every-point-ex-b7vz
If the distance between bombs[i] and bombs[j] is smaller than or equal to the radius of bombs[i], then we can detonate bombs[j] with bombs[i]. This relationship
zoo30215
NORMAL
2021-12-11T16:01:27.830540+00:00
2021-12-12T01:40:26.918247+00:00
1,993
false
If the distance between `bombs[i]` and `bombs[j]` is smaller than or equal to the `radius` of `bombs[i]`, then we can detonate `bombs[j]` with `bombs[i]`. This relationship can be viewed as an edge `i -> j`.\n\nWe can enumerate all bomb pairs to construct a directed graph with these detonation relationships. And then we start with every bomb, use BFS / DFS to find how many bombs that we can reach.\n\nTime Complexity:\n* Construct Graph: `O(N ** 2)`\n* DFS / BFS (one time) is `O(N ** 2)` since there are at most `O(N ** 2)` edges in the constructed graph. We do BFS `N` times, so the worst complexity is `O(N ** 3)`.\n\n```python\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n \n N = len(bombs)\n \n # construct directed graph\n G = defaultdict(list)\n for i in range(N):\n for j in range(N):\n if i == j:\n continue\n bi = bombs[i]\n bj = bombs[j]\n if (bi[0] - bj[0]) ** 2 + (bi[1] - bj[1]) ** 2 <= bi[2] ** 2:\n G[i].append(j)\n\n # apply DFS with every bomb as start point\n max_ans = 1\n for start in range(N):\n queue = [start]\n visited = set([start])\n this_ans = 0\n while queue:\n pos = queue.pop()\n this_ans += 1\n for neib in G[pos]:\n if neib not in visited:\n queue.append(neib)\n visited.add(neib)\n max_ans = max(this_ans, max_ans)\n if max_ans == N:\n return N\n return max_ans\n```\n\n
11
1
[]
2
detonate-the-maximum-bombs
Python Elegant & Short | DFS
python-elegant-short-dfs-by-kyrylo-ktl-8vqb
Complexity\n- Time complexity: O(n^{2})\n- Space complexity: O(n^{2})\n\n# Code\n\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> i
Kyrylo-Ktl
NORMAL
2023-06-02T10:42:24.838031+00:00
2023-06-02T10:45:15.799515+00:00
2,287
false
# Complexity\n- Time complexity: $$O(n^{2})$$\n- Space complexity: $$O(n^{2})$$\n\n# Code\n```\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n def dfs(node: int, visited: set = None) -> set:\n if visited is None:\n visited = {node}\n\n for child in graph[node]:\n if child not in visited:\n visited.add(child)\n dfs(child, visited)\n\n return visited\n\n graph = defaultdict(set)\n\n for i, (x1, y1, rad) in enumerate(bombs):\n for j, (x2, y2, _) in enumerate(bombs):\n if (x1 - x2) ** 2 + (y1 - y2) ** 2 <= rad ** 2:\n graph[i].add(j)\n\n return max(len(dfs(i)) for i in range(len(bombs)))\n```
8
0
['Depth-First Search', 'Graph', 'Python', 'Python3']
1
detonate-the-maximum-bombs
Why is this wrong? Python Union Find Solution passes 111/160
why-is-this-wrong-python-union-find-solu-cfjg
\nclass UnionF:\n def __init__(self, n):\n self.rank = [1 for _ in range(n)]\n self.par = [i for i in range(n)]\n self.n = n\n \n
rsaxena123
NORMAL
2022-09-16T00:28:41.730641+00:00
2022-09-16T15:19:53.244866+00:00
1,276
false
```\nclass UnionF:\n def __init__(self, n):\n self.rank = [1 for _ in range(n)]\n self.par = [i for i in range(n)]\n self.n = n\n \n def find(self, n):\n # Path Compression + Finds root\n while n != self.par[n]:\n self.par[n] = self.par[self.par[n]]\n n = self.par[n]\n return n\n \n def union(self, n1, n2):\n p1, p2 = self.find(n1), self.find(n2)\n # If they aren\'t already unioned, union them\n if p1 != p2:\n if self.rank[p1] > self.rank[p2]:\n self.rank[p1] += 1\n self.par[p2] = p1\n else:\n self.rank[p2] += 1\n self.par[p1] = p2\n\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n n = len(bombs)\n union = UnionF(n)\n \n for i in range(n):\n for j in range(i):\n x1, y1, r1 = bombs[i][0], bombs[i][1], bombs[i][2]\n x2, y2, r2 = bombs[j][0], bombs[j][1], bombs[j][2]\n \n distance = sqrt((x2-x1)**2 + (y2-y1)**2)\n # Bombs would detonate eaach other\n if distance <= (r1 + r2):\n union.union(i, j) \n # Max rank is also the same as number of detonated bombs (connected componenets)\n return max(union.rank)\n```\nThis is the test case it is failing:\n[[54,95,4],[99,46,3],[29,21,3],[96,72,8],[49,43,3],[11,20,3],[2,57,1],[69,51,7],[97,1,10],[85,45,2],[38,47,1],[83,75,3],[65,59,3],[33,4,1],[32,10,2],[20,97,8],[35,37,3]]\n\nI return 2 bombs detonate each other but the answer is 1 bombs detonates.\n\nSpecificially the bombs: [65, 59, 3] [69, 51, 7] are 8.94427190999916 distance apart yet the problem says they should not detonate each other. Why is this so?\n
8
0
['Union Find', 'Python']
7
detonate-the-maximum-bombs
C++ || DFS || Connected Component Count
c-dfs-connected-component-count-by-bsh24-qqxz
\n\t\n\t// Function to calculate dis^2 between two points\n long long dis(int x1, int y1, int x2, int y2)\n {\n return pow(x2-x1,2) + pow(y2-y1,2);
bsh2409
NORMAL
2022-08-17T19:27:21.218174+00:00
2022-08-17T19:27:51.376845+00:00
1,448
false
\n\t\n\t// Function to calculate dis^2 between two points\n long long dis(int x1, int y1, int x2, int y2)\n {\n return pow(x2-x1,2) + pow(y2-y1,2);\n }\n // DFS connected components count\n void dfs(int node, vector<vector<int>> &adj, vector<bool>& visited , int &count)\n {\n if(visited[node]) return;\n \n visited[node]=true;\n \n // increment count each time we visit a new node\n count++;\n \n for(auto i: adj[node])\n if(!visited[i])\n dfs(i,adj,visited,count);\n }\n int maximumDetonation(vector<vector<int>>& bomb) {\n \n int n=bomb.size();\n \n vector<vector<int>> adj(n);\n \n // for every comparison of bomb i->j check if the distance between the center of those two\n // bombs is less than or equal to the radius of either of the bomb. If yes then push them\n // adj[i] = {j} means that if we trigger i, j will be triggered\n for(int i=0;i<n;i++)\n for(int j=i+1;j<n;j++)\n {\n long long r =dis(bomb[i][0],bomb[i][1],bomb[j][0],bomb[j][1]);\n if(r<= pow(bomb[i][2],2)) adj[i].push_back(j);\n if(r<= pow(bomb[j][2],2)) adj[j].push_back(i);\n }\n \n int ans=INT_MIN;\n \n vector<bool> visited;\n \n // perform DFS for every bomb\n for(int i=0;i<n;i++)\n {\n visited=vector(n,false);\n int count=0;\n dfs(i,adj,visited,count);\n ans=max(ans,count);\n }\n \n return ans;\n }\n\t\n
8
0
['Depth-First Search', 'C', 'C++']
1
detonate-the-maximum-bombs
need help with union find approach || cpp || uninon-find
need-help-with-union-find-approach-cpp-u-1yya
\nclass Solution {\npublic:\n long dist(long a,long b,long x,long y){\n return sqrt(pow((a-x+0ll),2.0) + pow((b-y+0ll),2.0));\n }\n // static b
meayush912
NORMAL
2021-12-11T16:09:51.985115+00:00
2021-12-11T16:09:51.985158+00:00
769
false
```\nclass Solution {\npublic:\n long dist(long a,long b,long x,long y){\n return sqrt(pow((a-x+0ll),2.0) + pow((b-y+0ll),2.0));\n }\n // static bool cmp(vector<int> &a,vector<int> &b){\n // return a[2]>b[2];\n // }\n int getp_(vector<int> &p,int x){\n if(p[x]==x)return x;\n return p[x]=getp_(p,p[x]);\n }\n void union_(vector<int> &p,vector<int> &r,int x,int y){\n int px=getp_(p,x) , py=getp_(p,y);\n if(px==py)return;\n \n if(r[px]>r[py]){\n p[py]=px;\n }else if(r[py]>r[px]){\n p[px]=py;\n }else{\n p[px]=py;\n r[py]++;\n }\n }\n int maximumDetonation(vector<vector<int>>& bmb) {\n int n=bmb.size();\n vector<int> p(n,0),r(n,0);\n \n for(int i=0;i<n;++i){\n p[i]=i;\n }\n \n \n for(int i=0;i<n;++i){\n for(int j=0;j<n;++j){\n // if(i!=j){\n int dt=dist(bmb[i][0],bmb[i][1],bmb[j][0],bmb[j][1]);\n if(dt<=bmb[i][2]){\n union_(p,r,i,j);\n }\n // }\n }\n }\n \n unordered_map<int,int> ump;\n int ans=1;\n for(int i=0;i<n;++i){\n ans=max(ans,++ump[getp_(p,i)]);\n }\n \n return ans;\n// vector<vector<int>> exp(bmb.size());\n// sort(bmb.begin(),bmb.end(),cmp);\n// for(int i=0;i<bmb.size();++i){\n// cout<<i<<" -> ";\n// for(int j=i+1;j<bmb.size();++j){\n// int dt=dist(bmb[i][0],bmb[i][1],bmb[j][0],bmb[j][1]);\n// if(dt<=bmb[i][2]){\n// exp[i].push_back(j);\n// cout<<j<<" ";\n// }\n// }\n// cout<<endl;\n// }\n \n// int ans=1;\n// vector<int> blast(bmb.size(),0);\n// for(int i=bmb.size()-1;i>=0;--i){\n// int t=1;\n// for(int j=0;j<exp[i].size();++j){\n// t+=blast[exp[i][j]];\n// }\n// blast[i]=t;\n// ans=max(ans,t);\n// }\n \n// return ans;\n }\n};\n```
8
0
[]
3
detonate-the-maximum-bombs
Java | DFS | Beats > 70% | Clean code
java-dfs-beats-70-clean-code-by-judgemen-2h48
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
judgementdey
NORMAL
2023-06-02T06:20:50.509832+00:00
2023-06-02T06:35:02.510602+00:00
1,627
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n private List<Integer>[] adj;\n private boolean[] seen;\n\n private int dfs(int node) {\n seen[node] = true;\n var cnt = 1;\n \n for (var neighbor : adj[node])\n if (!seen[neighbor])\n cnt += dfs(neighbor);\n \n return cnt;\n }\n\n public int maximumDetonation(int[][] bombs) {\n var max = 0;\n var n = bombs.length;\n seen = new boolean[n];\n adj = new ArrayList[n];\n\n for (var i=0; i<n; i++)\n adj[i] = new ArrayList<>();\n\n for (var i=0; i<n; i++) {\n for (var j=0; j<n; j++) {\n if (i == j) continue;\n\n var a = bombs[i];\n var b = bombs[j];\n\n if (Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2) <= Math.pow(a[2], 2))\n adj[i].add(j);\n }\n }\n for (var i=0; i<n; i++) {\n Arrays.fill(seen, false);\n max = Math.max(max, dfs(i));\n }\n return max;\n }\n}\n```\nIf you like my solution, please upvote it!
7
0
['Math', 'Depth-First Search', 'Graph', 'Geometry', 'Java']
0
detonate-the-maximum-bombs
Java Solution for Detonate the Maximum Bombs Problem
java-solution-for-detonate-the-maximum-b-0hal
Intuition\n Describe your first thoughts on how to solve this problem. \nThe given problem involves finding the maximum number of bombs that can be detonated by
Aman_Raj_Sinha
NORMAL
2023-06-02T02:54:48.346610+00:00
2023-06-02T02:54:48.346652+00:00
2,618
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe given problem involves finding the maximum number of bombs that can be detonated by choosing a single bomb. To solve this, we can represent the bombs as a graph, where each bomb is a node and there is an edge between two bombs if one can detonate the other. By using graph traversal techniques, such as Breadth-First Search (BFS), we can find the maximum number of detonated bombs.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Build the graph: Iterate over each pair of bombs and check if one bomb can detonate the other. If so, create a directed edge from the first bomb to the second bomb in the graph.\n1. Perform BFS: Iterate over each bomb and perform a BFS traversal starting from that bomb. Count the number of visited nodes during the traversal, which represents the number of detonated bombs.\n1. Update the maximum count: Keep track of the maximum detonated count encountered during the BFS traversal.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of building the graph is O(n^2) since we iterate over each pair of bombs. The BFS traversal is performed for each bomb, which has a time complexity of O(n + m), where n is the number of nodes (bombs) and m is the number of edges in the graph. In the worst case, the number of edges can be O(n^2), resulting in a time complexity of O(n^3). However, on average, the number of edges tends to be much smaller, resulting in an average time complexity closer to O(n^2).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(n^2) to store the graph using a HashMap, where n is the number of bombs. Additionally, the BFS traversal requires O(n) space for the queue and O(n) space for the visited set, resulting in a total space complexity of O(n^2 + n + n) = O(n^2).\n\n# Code\n```\nclass Solution {\n public int maximumDetonation(int[][] bombs) {\n Map<Integer, List<Integer>> graph = new HashMap<>();\n int n = bombs.length;\n \n // Build the graph\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n int xi = bombs[i][0], yi = bombs[i][1], ri = bombs[i][2];\n int xj = bombs[j][0], yj = bombs[j][1];\n \n // Create a path from node i to node j, if bomb i detonates bomb j.\n if ((long)ri * ri >= (long)(xi - xj) * (xi - xj) + (long)(yi - yj) * (yi - yj)) {\n graph.computeIfAbsent(i, k -> new ArrayList<>()).add(j);\n }\n }\n }\n \n int answer = 0;\n for (int i = 0; i < n; i++) {\n answer = Math.max(answer, bfs(i, graph));\n }\n \n return answer;\n }\n \n private int bfs(int i, Map<Integer, List<Integer>> graph) {\n Deque<Integer> queue = new ArrayDeque<>();\n Set<Integer> visited = new HashSet<>();\n queue.offer(i);\n visited.add(i);\n while (!queue.isEmpty()) {\n int cur = queue.poll();\n for (int neib : graph.getOrDefault(cur, new ArrayList<>())) {\n if (!visited.contains(neib)) {\n visited.add(neib);\n queue.offer(neib);\n }\n }\n }\n return visited.size();\n }\n}\n```
7
0
['Java']
0
detonate-the-maximum-bombs
JAVA Solution | DFS Traversal
java-solution-dfs-traversal-by-piyushja1-uu1a
We just need to find out the maximum no. of connected components i.e. bombs\n\nclass Solution {\n \n public int maximumDetonation(int[][] bombs) {\n
piyushja1n
NORMAL
2021-12-12T06:52:14.657178+00:00
2021-12-12T06:52:14.657209+00:00
948
false
We just need to find out the maximum no. of connected components i.e. bombs\n```\nclass Solution {\n \n public int maximumDetonation(int[][] bombs) {\n \n List<List<Integer>> adj = new ArrayList<>();\n int n = bombs.length;\n boolean[] vis = new boolean[n];\n int max=1;\n \n \n for(int i=0;i<n;i++)\n adj.add(new ArrayList<>());\n \n for(int i=0;i<n;i++){\n long x = (long)bombs[i][0],y=(long)bombs[i][1],r=(long)bombs[i][2];\n \n for(int j=0;j<n;j++){\n int x1 = bombs[j][0],y1=bombs[j][1],r1=bombs[j][2];\n \n if(i!=j){\n if((((x-x1)*(x-x1)+(y-y1)*(y-y1))<=r*r))\n adj.get(i).add(j);\n }\n }\n }\n\n \n for(int i=0;i<n;i++){\n int ans = DFS(i,adj,vis);\n Arrays.fill(vis,false);\n max = Math.max(ans,max);\n }\n \n return max;\n \n }\n \n private int DFS(int i,List<List<Integer>> adj,boolean []vis){\n vis[i]=true;\n int ans =1;\n for(int nd : adj.get(i)){\n if(!vis[nd])\n ans+=DFS(nd,adj,vis);\n }\n \n return ans;\n }\n}\n```
7
0
[]
1
detonate-the-maximum-bombs
C++ || Using BFS
c-using-bfs-by-rajdeep_nagar-3kqo
As its mentioned in first Solved example that for any two Bombs A-B , B will blast due to effect of A if and only if Centre of B lies inside or on the circumfer
Rajdeep_Nagar
NORMAL
2021-12-11T17:40:26.398534+00:00
2021-12-12T04:10:37.823568+00:00
747
false
As its mentioned in first Solved example that for any two Bombs A-B , B will blast due to effect of A if and only if Centre of B lies inside or on the circumference of A => radius of Bomb A (r1) >= Distance between their centers.\n\nSo We start bfs from Bomb i and including all those bombs in effect of A that satisfies above condition.\n\n```\n#define lln long long int\nclass Solution {\n int mx=INT_MIN;\n queue<int>q;\n\npublic:\n int maximumDetonation(vector<vector<int>>& bombs) {\n \n int n=bombs.size();\n \n for(int i=0;i<n;i++){\n bfs(i,bombs);\n }\n \n return mx;\n }\n \n void bfs(int i, vector<vector<int>>& bombs){\n int n=bombs.size();\n vector<bool>vis(n,false);\n \n lln x1,y1,r1,x2,y2,r2;\n q.push(i);\n vis[i]=true;\n \n int count=1;\n \n while(!q.empty()){\n \n int j=q.front();\n vis[j]=true;\n q.pop();\n \n for(int k=0;k<n;k++){\n if(vis[k]==true)\n continue;\n \n x1=bombs[j][0],y1=bombs[j][1],r1=bombs[j][2];\n x2=bombs[k][0],y2=bombs[k][1],r2=bombs[k][2];\n \n if(r1 >= sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)) ) {\n vis[k]=true;\n q.push(k);\n count++;\n }\n }\n \n }\n \n mx=max(mx,count);\n }\n};\n```
7
0
['Breadth-First Search']
4
detonate-the-maximum-bombs
[C++] | BFS | Beginner - Friendly | O(N^3)
c-bfs-beginner-friendly-on3-by-doraemon-8ld0
\nclass Solution {\npublic:\n long long int cnt;\n long long get(vector<vector<int> > &ar, int i, int n){\n vector<int> vis(n,0);\n queue<ve
Doraemon_
NORMAL
2021-12-11T16:15:17.047325+00:00
2022-02-13T06:47:02.501975+00:00
606
false
```\nclass Solution {\npublic:\n long long int cnt;\n long long get(vector<vector<int> > &ar, int i, int n){\n vector<int> vis(n,0);\n queue<vector<int> > q;\n \n vis[i] = 1;\n cnt++;\n \n q.push(ar[i]);\n while(!q.empty()){\n auto cur = q.front();\n q.pop();\n \n for(int j = 0; j < n; j++){\n if(!vis[j]){\n long long int a = (ar[j][0] * 1ll - cur[0] * 1ll) * (ar[j][0] * 1ll - cur[0] * 1ll); \n long long int b = (ar[j][1] * 1ll - cur[1] * 1ll) * (ar[j][1] * 1ll - cur[1] * 1ll);\n long long int c = cur[2] * 1ll * cur[2];\n \n // Check whether centre of new circle lies \n // on or inside the current circle\n long long int k = a + b - c;\n if(k <= 0){\n vis[j] = 1;\n q.push(ar[j]);\n cnt++;\n }\n }\n }\n }\n return cnt;\n }\n int maximumDetonation(vector<vector<int>>& ar) {\n int n = ar.size();\n long long int ans = -1;\n \n for(int i = 0; i < n; i++){\n cnt = 0;\n ans = max(ans, get(ar, i, n));\n }\n \n return ans;\n }\n};\n```\nDo Upvote, If it helps!
7
0
['Breadth-First Search']
1
detonate-the-maximum-bombs
✅ [Python] DFS || Explained || Easy to Understand || Faster 100%
python-dfs-explained-easy-to-understand-du1s6
First Construct a graph, each bomb as a vertex, if b is within the explosion radius of a, then there is a directed edge from a to b. Construct the adjacency mat
linfq
NORMAL
2021-12-11T16:11:00.505249+00:00
2021-12-11T16:53:56.740805+00:00
1,316
false
* First Construct a graph, each bomb as a vertex, if b is within the explosion radius of a, then there is a directed edge from a to b. Construct the adjacency matrix of the Directed graph.\n\t* Note that this is a directed graph, so we cannot use UnionFindSet.\n* Traverse each bomb as the starting point and count the number of nodes it can reach on graph.\n* Return the max count number.\n```\nclass Solution(object):\n def maximumDetonation(self, bombs):\n def count(i):\n dq, ret = [i], [i]\n while len(dq) > 0:\n i = dq.pop()\n for j in adj[i]:\n if j not in ret and j not in dq:\n dq.append(j)\n ret.append(j)\n return len(ret)\n\n adj = collections.defaultdict(list)\n for i in range(len(bombs)):\n for j in range(i + 1, len(bombs)):\n if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[i][2] ** 2:\n adj[i].append(j)\n if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[j][2] ** 2:\n adj[j].append(i)\n ret = 0\n for i in range(len(bombs)):\n ret = max(ret, count(i))\n return ret\n```\n**Please UPVOTE!**
7
0
['Python']
4
detonate-the-maximum-bombs
Understandable Explanation | Graph visualized
understandable-explanation-graph-visuali-9wv0
Intuition\n Describe your first thoughts on how to solve this problem. \nHow can we visiualize the problem?\nWhich data structure should we use ?\n\nThe key to
Anuj_vanced
NORMAL
2023-06-02T14:00:35.772423+00:00
2023-06-02T14:00:35.772463+00:00
479
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHow can we visiualize the problem?\nWhich data structure should we use ?\n\nThe key to the solution is just visualization, if you crack that this question is a piece of cake.\n\nThink of a single detonation some other bombs and those other bombs are detonating further or they even might detonate a previous one.\nAren\'t you getting a feel of chain. A chain which might contain cycles , or some disconnected parts .\nWe can visualize bombs as vertices with their detonation connection as directed edge between them.\nAlso look at the constraints first we do not have to worry about time complexity much, an n^2 solution with be fairly good.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nImplement an inRange(bomb a,bomb b) funciton to check weather bomb b is in the range of a or not. You can easily check using basic co-ordinate geometry (remember class 12). I am shifting origin to co-ordinates of bomb a and checking now if co-ordinates of other bomb will lie in the range (x*x + y*y <= r*r) it will get detonated.\n\nNow create a directed graph with all pairs of (i,j) (i and j here represents bombs 0,1,2....n-1) and check if j is in the range of i there will be an edge from i to j.\n\nNow the question to just count the maximum number of reachable node from a single node and as we can go for O(n^2) we can simply run a bfs or dfs traversal from every node and count the number of nodes and return the maximum.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int n;\n \n bool inRange(vector<int> v1,vector<int> v2)\n {\n long long x1 = v1[0],y1 = v1[1] , r = v1[2];\n long long x2 = v2[0] , y2 = v2[1];\n\n x2 -= x1;\n y2 -= y1;\n\n if(x2*x2 + y2*y2 <= r*r) return true;\n return false;\n }\n\n int bfs(unordered_map<int,vector<int>> &adj,int node)\n {\n queue<int> q;\n vector<bool> visited(n+1,false); \n visited[node]=true;\n q.push(node);\n int ans = 0;\n while(!q.empty())\n {\n ans++;\n\n int temp = q.front();\n \n q.pop();\n for(auto i : adj[temp])\n {\n if(!visited[i]) q.push(i);\n visited[i] = true;\n }\n }\n\n return ans;\n }\n int maximumDetonation(vector<vector<int>>& bombs)\n {\n n = bombs.size();\n\n unordered_map<int,vector<int>> adj;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(i==j) continue;\n\n if(inRange(bombs[i],bombs[j]))\n {\n adj[i+1].push_back(j+1);\n }\n }\n }\n\n int ans = -1;\n \n for(int i=1;i<=n;i++)\n {\n ans = max(ans,bfs(adj,i));\n \n }\n\n return ans;\n }\n};\n```
6
0
['Graph', 'C++']
0
detonate-the-maximum-bombs
🏆C++ || Easy DFS
c-easy-dfs-by-chiikuu-4g9b
Code\n\nclass Solution\n{\npublic:\n int dfs(vector<int> &v, vector<vector<int>> &b, int i)\n {\n v[i] = 1;\n int x = b[i][0], y = b[i][1];\
CHIIKUU
NORMAL
2023-06-02T07:57:24.164869+00:00
2023-06-02T07:57:24.164913+00:00
1,579
false
# Code\n```\nclass Solution\n{\npublic:\n int dfs(vector<int> &v, vector<vector<int>> &b, int i)\n {\n v[i] = 1;\n int x = b[i][0], y = b[i][1];\n int r = b[i][2];\n int j = 0;\n int ans = 1;\n for (int j = 0; j < b.size(); j++)\n {\n long long g = abs(x - b[j][0]);\n g *= g;\n long long gg = abs(y - b[j][1]);\n gg *= gg;\n double dis = sqrt(g + gg);\n if (dis <= (r) && !v[j])\n {\n ans += dfs(v, b, j);\n }\n }\n return ans;\n }\n int maximumDetonation(vector<vector<int>> &b)\n {\n int n = b.size();\n int ans = 0;\n for (int i = 0; i < n; i++)\n {\n vector<int> v(n, 0);\n if (!v[i])\n {\n ans = max(ans, dfs(v, b, i));\n }\n }\n return ans;\n }\n};\n```\n![upvote (2).jpg](https://assets.leetcode.com/users/images/a5d5993c-bc66-4076-8557-f5928282fe17_1685692639.1890407.jpeg)\n
6
0
['C++']
2
detonate-the-maximum-bombs
C++ | Graphs + Math | Explained
c-graphs-math-explained-by-jk20-68n5
Approach :\n\n Since the constraints are low i.e we are given only 100 bombs at max, we can, for each bomb we can find if we detonate this bomb, how many other
jk20
NORMAL
2022-03-18T04:01:25.027530+00:00
2022-03-18T04:01:25.027573+00:00
894
false
**Approach :**\n\n* Since the constraints are low i.e we are given only 100 bombs at max, we can, for each bomb we can find if we detonate this bomb, how many other bombs it can detonate. \n\n* Now we can represent bombs as nodes in graph. \n* Also we need to revisit our High School Geometry, to check if a point lies outside circle or inside or on the circumference, that can be done by checking the distance between the point and centre of other circle.\n* Now if distance is greater than radius of other circle, then we cannot detonate that bomb, according to the question.\n* Then after finding the relation between bombs we can run DFS to find how many other bombs a single bomb, if detonated, can detonate.\n\n```\nclass Solution {\npublic:\n double eucDis(int x1,int y1,int x2,int y2)\n {\n double temp=pow(x1-x2,2)+pow(y1-y2,2);\n return sqrt(temp);\n }\n void dfs(int node,vector<int>&vis,vector<int>graph[],int &c)\n {\n c++;\n vis[node]=1;\n for(auto i:graph[node])\n {\n if(!vis[i])\n {\n dfs(i,vis,graph,c);\n }\n }\n }\n int maximumDetonation(vector<vector<int>>& bombs) {\n \n int n=bombs.size();\n vector<int>graph[n+1];\n int i,j;\n for(i=0;i<n;i++)\n {\n bombs[i].push_back(i);\n }\n for(i=0;i<n;i++)\n {\n \n for(j=0;j<n;j++)\n {\n if(i==j)\n continue;\n double dis1=eucDis(bombs[i][0],bombs[i][1],bombs[j][0],\n bombs[j][1]);\n \n if(dis1<=bombs[i][2])\n {\n int node1=bombs[i][3];\n int node2=bombs[j][3];\n graph[node1].push_back(node2);\n }\n }\n }\n \n int maxi=1;\n for(i=0;i<n;i++)\n {\n int c=0;\n if(graph[i].empty())\n continue;\n vector<int>vis(n+1,0);\n \n dfs(i,vis,graph,c); \n maxi=max(maxi,c);\n \n \n }\n return maxi;\n }\n};\n```\n\n**Runtime: 110 ms, faster than 78.69% of C++ online submissions for Detonate the Maximum Bombs.**\n\n\n**Memory Usage: 17.2 MB, less than 56.73% of C++ online submissions for Detonate the Maximum Bombs.**\n\n\n**Pls upvote the solution if you found helpful, it means a lot.\nAlso comment down your doubts.\nHappy Coding : )**
6
0
['Depth-First Search', 'Breadth-First Search', 'Graph', 'Recursion', 'C', 'C++']
0