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
detonate-the-maximum-bombs
JavaScript - DFS Solution
javascript-dfs-solution-by-harsh07bharva-fwbu
\n/**\n * @param {number[][]} bombs\n * @return {number}\n */\nvar maximumDetonation = function(bombs) {\n if(bombs.length <= 1) return bombs.length;\n \n
harsh07bharvada
NORMAL
2021-12-21T04:25:29.956323+00:00
2021-12-21T04:25:29.956359+00:00
1,161
false
```\n/**\n * @param {number[][]} bombs\n * @return {number}\n */\nvar maximumDetonation = function(bombs) {\n if(bombs.length <= 1) return bombs.length;\n \n let adj = {}, maxSize = 0;\n const checkIfInsideRange = (x, y, center_x, center_y, radius) =>{\n return ( (x-center_x)**2 + (y-center_y)**2 <= radius**2 ) \n }\n\t\n\t//CREATE ADJACENCY MATRIX\n for(let i = 0;i<bombs.length;i++){\n for(let j = i+1;j<bombs.length;j++){\n if(!adj[i]) adj[i] = [];\n if(!adj[j]) adj[j] = [];\n let bombOne = bombs[i];\n let bombTwo = bombs[j];\n let fir = checkIfInsideRange(bombOne[0], bombOne[1], bombTwo[0], bombTwo[1], bombOne[2]); \n if(fir) adj[i].push(j);\n let sec = checkIfInsideRange(bombOne[0], bombOne[1], bombTwo[0], bombTwo[1], bombTwo[2]);\n if(sec) adj[j].push(i);\n }\n }\n\t\n\t//DEPTH FIRST SEARCH TO FIND ALL BOMBS TRIGGERED BY NODE\n const dfs = (node, visited)=>{\n let detonated = 1;\n visited[node] = true;\n let childs = adj[node] || []\n for(let child of childs){\n if(visited[child]) continue;\n detonated += dfs(child, visited)\n }\n maxSize = Math.max(maxSize, detonated)\n return detonated;\n }\n \n for(let i = 0 ;i<bombs.length;i++){\n dfs(i, {})\n }\n return maxSize\n};\n```
6
0
['Depth-First Search', 'JavaScript']
0
detonate-the-maximum-bombs
✅ [c++] || BFS
c-bfs-by-xor09-m5ui
\n#define ll long long\nclass Solution {\npublic:\n bool isInside(ll circle_x, ll circle_y, ll rad, ll x, ll y){\n if ((x - circle_x) * (x - circle_x)
xor09
NORMAL
2021-12-17T14:31:16.141895+00:00
2021-12-17T14:31:16.141922+00:00
541
false
```\n#define ll long long\nclass Solution {\npublic:\n bool isInside(ll circle_x, ll circle_y, ll rad, ll x, ll y){\n if ((x - circle_x) * (x - circle_x) + (y - circle_y) * (y - circle_y) <= rad * rad) return true;\n else return false;\n }\n \n int bfs(int i, unordered_map<int,vector<int>> &map, int n){\n vector<int> vis(n,false);\n queue<int> q;\n q.push(i);\n vis[i] = true;\n int count=0;\n while(!q.empty()){\n int cur = q.front(); q.pop();\n count++;\n for(auto &child : map[cur]){\n if(vis[child]==false){\n q.push(child);\n vis[child] = true;\n } \n }\n }\n return count;\n }\n \n int maximumDetonation(vector<vector<int>>& bombs) {\n int n = bombs.size();\n unordered_map<int,vector<int>> map;\n \n for(int i=0; i<n; ++i){\n int circle_x = bombs[i][0];\n int circle_y = bombs[i][1];\n int rad = bombs[i][2];\n for(int j=0; j<n; ++j){\n if(i!=j){\n int x = bombs[j][0];\n int y = bombs[j][1];\n if(isInside(circle_x, circle_y, rad, x, y)) map[i].push_back(j);\n } \n }\n }\n \n int maxDefuse = 0;\n for(int i=0; i<n; ++i){\n maxDefuse = max(maxDefuse, bfs(i,map,n));\n }\n return maxDefuse;\n }\n};\n```\nPlease **UPVOTE**
6
0
['Breadth-First Search', 'Graph', 'C', 'C++']
0
detonate-the-maximum-bombs
Easy Math and Graph Solution || C++
easy-math-and-graph-solution-c-by-abhi_p-dvob
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
abhi_pandit_18
NORMAL
2023-06-02T16:36:21.876764+00:00
2023-06-02T16:36:21.876801+00:00
50
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#define ll long long int\nclass Solution {\n public:\n void dfs(vector<vector<int>> &adj,vector<bool> &visited,int &c,int &i) {\n visited[i]=true;\n c++;\n for(auto it:adj[i]) {\n if(!visited[it])\n dfs(adj,visited,c,it); \n }\n }\n\n int maximumDetonation(vector<vector<int>>& bombs) {\n\n int n=bombs.size();\n vector<vector<int> > adj(n);\n for(int i=0;i<n;i++) {\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 if(i!=j) {\n ll x,y;\n x=abs(x1-bombs[j][0]);\n y=abs(y1-bombs[j][1]);\n if(x*x+y*y<=r1*r1)\n adj[i].push_back(j);\n }\n }\n }\n\n int ans=INT_MIN;\n for(int i=0;i<n;i++) {\n int c=0;\n vector<bool> visited(n,false);\n dfs(adj,visited,c,i);\n ans=max(ans,c);\n }\n\n return ans;\n }\n};\n```
5
0
['C++']
0
detonate-the-maximum-bombs
Detonate Maximum Bombs, C++ Explained Solution
detonate-maximum-bombs-c-explained-solut-8uw3
The problem here can be solved in 2 ways. Using BFS or DFS. We have discussed BFS here because it can reduce down the code needed in DFS to form the graph first
ShuklaAmit1311
NORMAL
2022-07-15T09:07:23.021802+00:00
2022-07-15T09:07:23.021844+00:00
659
false
The problem here can be solved in 2 ways. Using **BFS** or **DFS**. We have discussed BFS here because it can reduce down the code needed in DFS to form the graph first. Basically if you see, we have been given a **DIRECTED GRAPH**. Note : **The graph might not be a DAG (Directed Acyclic Graph) cause it might be possible that a series of bombs might blast each other thus forming a cycle. So specifically we are only given a directed graph.** Now simply what we can do is choose each bomb and then perform BFS to obtain all bombs that might get detonated and take maximum among all choices. The implementation is given below :\n\nTime Complexity : O(N^2)\nSpace Complexity : O(N)\n\nCode\n```\nclass Solution {\npublic:\n int maximumDetonation(vector<vector<int>>& bombs) {\n ios_base::sync_with_stdio(0);\n int n = bombs.size();\n int maxbombs = 0; vector<bool>visited(n,false);\n for(int i = 0; i<n; i++){\n queue<int>q; int countbombs = 0;\n q.push(i);\n while(!q.empty()){\n int u = q.front(); q.pop();\n countbombs++;\n visited[u] = true;\n long long x = bombs[u][0],y = bombs[u][1],r = bombs[u][2];\n for(int j = 0; j<n; j++){\n if(!visited[j]){\n long long dx = bombs[j][0],dy = bombs[j][1],rd = bombs[j][2];\n long long dis = (x-dx)*(x-dx)+(y-dy)*(y-dy);\n if(dis<=r*r){\n visited[j] = true;\n q.push(j);\n }\n }\n }\n }\n maxbombs = max(maxbombs,countbombs);\n for(int i = 0; i<n; i++){\n visited[i] = false;\n }\n }\n return maxbombs;\n }\n};\n```\n\n**Do Upvote If Found Helpful !**
5
0
['Depth-First Search', 'Breadth-First Search', 'Graph', 'C']
2
detonate-the-maximum-bombs
Video solution | Intuition explained in detail | C++ | BFS | Hindi
video-solution-intuition-explained-in-de-0amh
Video\nHey everyone i have created a video solution for this problem (its in hindi), it involves intuitive explanation with code, this video is part of my playl
_code_concepts_
NORMAL
2024-10-30T09:51:04.944331+00:00
2024-10-30T09:59:21.627138+00:00
339
false
# Video\nHey everyone i have created a video solution for this problem (its in hindi), it involves intuitive explanation with code, this video is part of my playlist "Master Graphs"\nVideo link : https://youtu.be/hkD8JUuWbkA\nPlaylist link: : https://www.youtube.com/playlist?list=PLICVjZ3X1AcZ5c2oXYABLHlswC_1LhelY\n\n\n\n# Code\n```cpp []\n\n#define ll long long\nclass Solution {\npublic:\n\n int bfs(int i, unordered_map<int,vector<int>> &graph, int n){\n int count=0;\n vector<int> visited(n,false);\n queue<int> q;\n q.push(i);\n visited[i]=true;\n while(!q.empty()){\n int curr=q.front();\n q.pop();\n count++;\n for(auto &bomb: graph[curr]){\n if(!visited[bomb]){\n q.push(bomb);\n visited[bomb]=true;\n }\n }\n }\n return count;\n\n }\n\n bool checkIfInside(ll curr_x, ll curr_y,ll curr_rad,ll x,ll y){\n if((curr_x-x)*(curr_x-x) + (curr_y-y)*(curr_y-y) <= curr_rad*curr_rad) return true;\n return false;\n }\n int maximumDetonation(vector<vector<int>>& bombs) {\n int n= bombs.size();\n unordered_map<int,vector<int>> graph;\n\n for(int i=0;i<n;i++){\n int curr_x= bombs[i][0];\n int curr_y= bombs[i][1];\n int curr_rad= bombs[i][2];\n for(int j=0;j<n;j++){\n if(i!=j){\n int x= bombs[j][0];\n int y= bombs[j][1];\n if(checkIfInside(curr_x,curr_y,curr_rad,x,y)){\n graph[i].push_back(j);\n }\n }\n }\n\n }\n int ans=0;\n for(int i=0;i<n;i++){\n ans=max(ans, bfs(i, graph,n));\n }\n\n return ans;\n\n\n\n }\n};\n```
4
0
['C++']
0
detonate-the-maximum-bombs
EASY 5 POINTER APPROACH || BFS || GRAPH
easy-5-pointer-approach-bfs-graph-by-abh-dh6d
Intuition\n Describe your first thoughts on how to solve this problem. \nThe algorithm aims to find the maximum number of bombs that can be detonated by choosin
Abhishekkant135
NORMAL
2023-12-13T01:06:34.481714+00:00
2023-12-13T01:06:34.481735+00:00
214
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe algorithm aims to find the maximum number of bombs that can be detonated by choosing only one bomb and triggering its chain reaction.\nBFS is an option to solve this problem as in this case we gotta travel from ont to another bomb and then other to next.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Define a Pair class to represent the (x, y) coordinates and the detonation time of a bomb.\n2. Implement the distance method to calculate the Euclidean distance between two points.\n3. Implement the bfs method to perform breadth-first search (BFS) to find the number of bombs that can be detonated from a given bomb.\n4. In the maximumDetonation method, iterate through each bomb and find the maximum number of detonations by triggering that bomb.\n5. Return the maximum number of detonations.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N^2 * M)\nPLEASE UPVOTE\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n# Code\n```\nclass Pair {\n int x;\n int y;\n int time;\n\n // Constructor to initialize Pair with x, y, and time\n public Pair(int x, int y, int time) {\n this.x = x;\n this.y = y;\n this.time = time;\n }\n}\n\nclass Solution {\n // Helper method to calculate Euclidean distance between two points\n public double distance(int x1, int y1, int x2, int y2) {\n int deltaX = x2 - x1;\n int deltaY = y2 - y1;\n return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));\n }\n\n // Helper method to perform breadth-first search (BFS)\n public int bfs(int x, int y, int time, int[][] bombs) {\n int visit[] = new int[bombs.length];\n int count = 0;\n Queue<Pair> q = new LinkedList<>();\n q.add(new Pair(x, y, time));\n\n while (!q.isEmpty()) {\n int x1 = q.peek().x;\n int y1 = q.peek().y;\n int tym = q.peek().time;\n q.remove();\n\n for (int i = 0; i < bombs.length; i++) {\n if (distance(x1, y1, bombs[i][0], bombs[i][1]) <= tym && visit[i] == 0) {\n q.add(new Pair(bombs[i][0], bombs[i][1], bombs[i][2]));\n visit[i] = 1;\n count++;\n }\n }\n }\n\n return count;\n }\n\n // Main method to find the maximum number of detonations\n public int maximumDetonation(int[][] bombs) {\n int n = bombs.length;\n int ans = 0;\n\n for (int i = 0; i < n; i++) {\n ans = Math.max(bfs(bombs[i][0], bombs[i][1], bombs[i][2], bombs), ans);\n }\n\n return ans;\n }\n}\n\n```
4
0
['Breadth-First Search', 'Graph', 'Java']
0
detonate-the-maximum-bombs
C# | BFS | Detailed Explanation + Dry Run | Runtime Beats 87.47%
c-bfs-detailed-explanation-dry-run-runti-nld6
Intuition\nWhile reading the problem we get to understand that this is a sort of problem where a relationship needs to be established between bombs so that when
anaken
NORMAL
2023-07-15T07:43:33.122914+00:00
2023-07-15T08:58:28.354843+00:00
114
false
# Intuition\nWhile reading the problem we get to understand that this is a sort of problem where a relationship needs to be established between bombs so that when one explodes the other one does too. This becomes more clearer by the fact that the range is involved while deciding that. So with this information it becomes clear that it is a graph problem. Most of the graph problems revolve around 4 algorithms, DFS, BFS, Union Find and Topological Sort. Also one problem can be solved by more than one of these algorithms. Since we need to detonate maximum number of bombs by detonating a single bomb so at any given time all the children of a node are coming into the picture and hence BFS is the algorithm we will go with.\n\n# Approach\n\n**Example used - bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]**\n\n**Adjacency List Creation**\n\nOur solution starts by building the Adjacency List of the form in the image. This kind of structure can be used to represent both a directed and an undirected graph, the difference being that in undirected we will be adding two edges for each relationship, one for each node involved whereas in directed just one edge is added. In our case we will be using a directed graph since bomb 1 being in the range of bomb 2 does not mean it is true the other way around as the ranges differ for both of them even though the distance remains same.\nWe will be using the mathematical formula to calculate distance between any two bombs. If the range of the first bomb is greater than the calculated distance, we can assume that bomb 2 will detonate on the detonation of bomb 1 and hence there a directed edge from bomb 1 to bomb 2.\nOnce our Adjacency list is ready we need a way to find a way to detonate maximum bombs. For this we will be using the breadth first search algorithm to iterate over all nodes in the graph, then run the BFS for each of them since we don\'t know which bomb will detonate all the bombs. We also maintain the \'maxBombsDetonated\' state so that at any point if we detonate all bombs we don\'t need to iterate further and can exit then and there.\n\n![image.png](https://assets.leetcode.com/users/images/844c794c-7c05-4657-b355-f313133fb705_1689405355.7905874.png)\n\n\n**How BFS works**\n\nBreadth First Search is an algorithm to traverse the nodes of a graph in a breadth wise manner, what it means is instead of going in one direction straight like in DFS, we want to iterate over the current node as well as over all its children before moving onto a new node and its children thereafter, so in this manner we go level by level instead of in one direction depth wise. For BFS algorithm we use Queue data structure since it helps to preserve the order of insertion.\nThe exist condition for this is generally the queue count becoming zero as no more nodes are left to process. Also another important point is that we need to maintain a \'visited\' set inorder to not detonate a bomb again which has already been detonated since there could be a case in which we come back to the node from which we started via some other intermediate node.\nIn the below image I have shown a dry run for the example.\nHere since the first iteration with i = 0 itself detonates all 5 bombs we don\'t to traverse further and the code exists.\n\n![image.png](https://assets.leetcode.com/users/images/84407e38-69a9-42cc-9741-d5dc55121406_1689406682.9492385.png)\n\n# **If you found my solution and explanation helpful, please consider upvoting it. Your upvote will help rank it higher among other solutions, making it easier for people seeking assistance to find. Feel free to ask any follow-up questions in the comment section. Thank you for reading!**\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\nInitializing the adjacency list: O(n)\n\nThe code initializes the adjacency list by creating a new list for each vertex. This takes O(n) time, where n is the number of bombs.\nConstructing the adjacency list: O(n^2)\n\nThe code constructs the adjacency list by checking the distance between each pair of bombs and adding an edge if they are adjacent. This involves nested loops, where the outer loop runs n times and the inner loop also runs n times. Therefore, this step takes O(n^2) time.\nBFS traversal: O(n + m)\n\nThe code performs a BFS traversal on the adjacency list. The time complexity of BFS is O(V + E), where V is the number of vertices and E is the number of edges. In this case, the number of vertices is n, and the number of edges is the sum of the sizes of all lists in the adjacency list, which can be denoted as m. Therefore, the BFS traversal takes O(n + m) time.\nMain loop: O(n * (n + m))\n\nThe code iterates over each vertex and performs a BFS traversal on it. Since the BFS traversal takes O(n + m) time, and this is done for each of the n vertices, the overall time complexity of the main loop is O(n * (n + m)).\nOverall, the time complexity of the given code is O(n^2 + n + m), which can be simplified to O(n^2 + m) in the worst case.\n# Code\n```\npublic class Solution {\n List<int>[] adjacencyList;\n public int MaximumDetonation(int[][] bombs) \n {\n int n = bombs.Length;\n adjacencyList = new List<int>[n];\n int maxBombsDetonated = 0;\n\n for(int i = 0 ; i < n ; i++)\n {\n adjacencyList[i] = new List<int>();\n }\n\n for(int i = 0 ; i < n ; i++)\n {\n for(int j = 0 ; j < n ; j++)\n {\n if(i != j)\n {\n double dist = Math.Sqrt(Math.Pow((bombs[i][0]-bombs[j][0]),2) + Math.Pow((bombs[i][1] - bombs[j][1]),2));\n if(bombs[i][2] >= dist)\n {\n // bombs are adjacent if the second bomb lies in the range of first, drawing an edge from first to second\n adjacencyList[i].Add(j);\n }\n }\n }\n }\n\n for(int i = 0 ; i < n ; i++)\n {\n maxBombsDetonated = Math.Max(BFS(i),maxBombsDetonated);\n if(maxBombsDetonated == n)\n {\n return n;\n }\n }\n return maxBombsDetonated; \n }\n public int BFS(int i)\n {\n // Travsering the adjacencyList in BFS manner \n Queue<int> queue = new Queue<int>();\n HashSet<int> visited = new HashSet<int>();\n\n queue.Enqueue(i);\n visited.Add(i);\n\n while(queue.Count != 0)\n {\n int temp = queue.Dequeue();\n foreach(int curr in adjacencyList[temp])\n {\n if(!visited.Contains(curr))\n {\n queue.Enqueue(curr);\n visited.Add(curr);\n }\n }\n }\n return visited.Count;\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```
4
0
['Breadth-First Search', 'Graph', 'C#']
1
detonate-the-maximum-bombs
short and sweet JS solution using BFS
short-and-sweet-js-solution-using-bfs-by-8k9m
Intuition\nA new bomb explodes if its distance to the current bomb is less than the radius of the current bomb. \nWe can calculate this with a^2 + b^2 = c^2\nWe
Mister_CK
NORMAL
2023-06-02T20:54:38.173274+00:00
2024-04-07T21:00:42.686510+00:00
335
false
# Intuition\nA new bomb explodes if its distance to the current bomb is less than the radius of the current bomb. \nWe can calculate this with a^2 + b^2 = c^2\nWe can use BFS to check which bombs explodes, by adding exploding boms to our queue. \nWe have to check what the maximum number of exploding bombs is for each starting bomb, since order matters here, which is fine, since there are only 100 bombs\n\n# Approach\nBFS\n\n# Complexity\n- Time complexity:\nO(n^3)\n\n- Space complexity:\nnot sure, we only create one queue and one set at a time, so O(n)?\n# Code\n```\n/**\n * @param {number[][]} bombs\n * @return {number}\n */\nvar maximumDetonation = function(bombs) {\n let answer = 0\n for (let i = 0; i < bombs.length; i++) {\n const exploded = new Set([i])\n const queue = [bombs[i]]\n while(queue.length > 0) {\n const bomb = queue.shift()\n for (let j = 0; j < bombs.length; j++) {\n if (exploded.has(j)) continue\n const newBomb = bombs[j]\n const distance = ((Math.abs(newBomb[0] - bomb[0])**2 )+ (Math.abs(newBomb[1] - bomb[1])**2)) ** 0.5\n if (distance <= bomb[2]) {\n queue.push(newBomb)\n exploded.add(j)\n }\n }\n }\n answer = Math.max(exploded.size, answer)\n }\n return answer\n};\n```
4
0
['JavaScript']
3
detonate-the-maximum-bombs
Video Explanation - Math to Graph to DFS clear explanation [Java]
video-explanation-math-to-graph-to-dfs-c-9ljo
Approach\nhttps://youtu.be/hTqokf-HCqg\n\n# Similar Problems:\n\n- 463. Island Perimeter\n- 657. Robot Return to Origin\n- 200. Number of Islands\n- Number of I
hridoy100
NORMAL
2023-06-02T18:51:32.914083+00:00
2023-06-02T19:46:02.602271+00:00
978
false
# Approach\nhttps://youtu.be/hTqokf-HCqg\n\n# Similar Problems:\n\n- [463. Island Perimeter](https://leetcode.com/problems/island-perimeter/)\n- [657. Robot Return to Origin](https://leetcode.com/problems/robot-return-to-origin/)\n- [200. Number of Islands](https://leetcode.com/problems/number-of-islands/)\n- [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/)\n- [547. Number of Provinces](https://leetcode.com/problems/number-of-provinces/)\n- [2316. Count Unreachable Pairs of Nodes in an Undirected Graph](https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/)\n- [Number of Distinct Islands](https://leetcode.com/problems/number-of-distinct-islands/)\n- [Number of Connected Components in an Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)\n- [130. Surrounded Regions](https://leetcode.com/problems/surrounded-regions/)\n- [2658. Maximum Number of Fish in a Grid](https://leetcode.com/problems/maximum-number-of-fish-in-a-grid/)\n- [994. Rotting Oranges](https://leetcode.com/problems/rotting-oranges/)\n- [695. Max Area of Island](https://leetcode.com/problems/max-area-of-island/)\n- [529. Minesweeper](https://leetcode.com/problems/minesweeper/)\n\nI suggest you also solve the above mentioned problem. They can be solved using dfs, bfs or union find algorithms.\n\n# Complexity\n- Time complexity: $$O(N^3)$$\nBuilding the graph takes $$O(N^2)$$ time. The time complexity of a typical DFS is $$O(V+E)$$ where $$V$$ represents the number of nodes, and $$E$$ represents the number of edges. More specifically, there are $$n$$ nodes and $$n^2$$ edges in this problem. We need to perform $$n$$ depth-first searches.\n\n- Space complexity: The space complexity of DFS is $$(N^2)$$. \nThere are $$(n^2)$$ edges stored in **graph**.\n\n# Code (DFS):\n``` Java []\nclass Solution {\n int n;\n public int maximumDetonation(int[][] bombs) {\n int res = 0;\n n = bombs.length;\n for(int i=0; i<n; i++) {\n int[] bomb = bombs[i];\n boolean[] seen = new boolean[n];\n seen[i] = true;\n res = Math.max(res, dfs(bombs, i, seen, 1));\n }\n return res;\n }\n\n int dfs(int[][] bombs, int bombIndex, boolean[] seen, int detonate) {\n int[] curBomb = bombs[bombIndex];\n for(int i=0; i<n; i++) {\n if(i==bombIndex || seen[i]) {\n continue;\n }\n int[] bomb = bombs[i];\n int x1 = curBomb[0];\n int y1 = curBomb[1];\n long r1 = curBomb[2];\n\n int x2 = bomb[0];\n int y2 = bomb[1];\n int r2 = bomb[2];\n\n long dx = (x1-x2);\n long dy = (y1-y2);\n if(r1*r1 >= dx*dx + dy*dy) {\n seen[i] = true;\n detonate+=dfs(bombs, i, seen, 1);\n }\n }\n return detonate;\n }\n}\n```
4
0
['Depth-First Search', 'Java']
1
detonate-the-maximum-bombs
BFS SOLUTION
bfs-solution-by-abhai0306-zm3i
\nclass Pair\n{\n int x,y,r;\n Pair(int x,int y,int r)\n {\n this.x = x;\n this.y = y;\n this.r = r;\n }\n}\n\nclass Solution \
abhai0306
NORMAL
2023-06-02T03:06:38.285391+00:00
2023-06-02T03:06:38.285436+00:00
61
false
```\nclass Pair\n{\n int x,y,r;\n Pair(int x,int y,int r)\n {\n this.x = x;\n this.y = y;\n this.r = r;\n }\n}\n\nclass Solution \n{\n int max = 1 ,ans = 1;\n public int maximumDetonation(int[][] bombs) \n {\n \n for(int i=0;i<bombs.length;i++)\n {\n bfs(bombs,i);\n }\n \n return max;\n }\n \n void bfs(int bombs[][] ,int ind)\n {\n Queue<Pair> q = new LinkedList<>();\n q.offer(new Pair(bombs[ind][0],bombs[ind][1],bombs[ind][2]));\n boolean vis[] = new boolean[bombs.length];\n vis[ind] = true;\n ans = 1;\n \n while(!q.isEmpty())\n {\n int x = q.peek().x;\n int y = q.peek().y;\n int r = q.peek().r;\n q.poll();\n for(int i=0;i<bombs.length;i++)\n {\n if(vis[i] == true)\n continue;\n \n if(check(x,y,bombs[i][0],bombs[i][1],r) == true)\n {\n ans++;\n q.offer(new Pair(bombs[i][0],bombs[i][1],bombs[i][2]));\n vis[i] = true;\n } \n }\n }\n max = Math.max(max , ans);\n }\n\t\n boolean check(int x1 ,int y1 ,int x2, int y2 ,int r)\n {\n long dist = (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);\n \n if(r*r >= dist)\n return true;\n \n return false;\n }\n}\n```
4
0
['Breadth-First Search', 'Java']
0
detonate-the-maximum-bombs
C++ Easy to understand DFS solution
c-easy-to-understand-dfs-solution-by-jay-f0b3
Intuition\nWe select a bomb Bi to detonate first and then look for other bombs in range (let\'s say it is Bj), it form\'s a graph i.e, there exist a directed ed
jayantsaini0007
NORMAL
2023-02-15T14:43:50.472772+00:00
2023-02-15T14:43:50.472814+00:00
1,552
false
# Intuition\nWe select a bomb Bi to detonate first and then look for other bombs in range (let\'s say it is Bj), it form\'s a graph i.e, there exist a directed edge between bomb Bi and Bj and so on. Thus, DFS can be applied on each and every bomb in our array and max result can be checked after completion of each DFS.\n\n# Approach\n1. Declare ans as -1 or INT_MIN (any negative value).\n2. Select each bomb in the array as the first bomb to detonate.\n3. Create a hash table to keep record of already detonated bomb so that we don\'t count them more than once in our DFS (Similar to avoiding cycle in a graph).\n4. Call DFS.\n5. Go through each bomb that has not yet detonated.\n6. If the bomb Bj is in range i.e the distance between the bombs Bi and Bj in less than ri(radius of Bi) than Bj will explode so mark it visited and apply DFS on it and add the bombs that will detonate because of Bj to Bi. \n7. Return the number of bombs that can explode because of the detonation of ith bomb *(Note that curr_ans=1 because if a bomb is detonated than atleast it will explode even if no other bomb is in range).*\n8. Compare it with the earlier answer .\n# Complexity\n- Time complexity:\nO(n^3)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n long long distance(long long x1,long long y1,long long x2,long long y2){\n return (x2-x1)*(x2-x1)+(y2-y1)*(y2-y1);\n }\n int dfs(vector<vector<int>>&bombs,int i,map<int,bool>&visited){\n int curr_ans=1;\n \n for(int j=0;j<bombs.size();j++){\n if(j==i or visited[j]==true)continue;\n long long dis=distance(bombs[i][0],bombs[i][1],bombs[j][0],bombs[j][1]);\n if(dis<=bombs[i][2]*1LL*bombs[i][2]){\n visited[j]=true;\n curr_ans+=dfs(bombs,j,visited);\n }\n }\n return curr_ans;\n }\npublic:\n int maximumDetonation(vector<vector<int>>& bombs) {\n int ans=INT_MIN;\n for(int i=0;i<bombs.size();i++){\n map<int,bool>visited; //use unordered_map or vector for better time\n visited[i]=true;\n ans=max(ans,dfs(bombs,i,visited));\n }\n return ans;\n }\n};\n```
4
0
['Graph', 'C++']
0
detonate-the-maximum-bombs
Python BFS Faster than 96%
python-bfs-faster-than-96-by-welz-vjb7
Create a dictionary: the key is the index of each bomb, value is the indexes of all the bombs which the key bomb could detonate;\n2. Use BFS to calculate the nu
welz
NORMAL
2021-12-24T03:57:52.115787+00:00
2021-12-24T03:57:52.115814+00:00
814
false
1. Create a dictionary: the key is the index of each bomb, value is the indexes of all the bombs which the key bomb could detonate;\n2. Use BFS to calculate the number of bombs \n3. **No need to loop for all the keys in the dictionary,** for example:\nif bombs[3] can detonate bombs[4], bombs[5], bombs[6], so there is no need to calculate the detonated quantity of bombs 4,5 and 6;\ncause this question requires returning the maximum quantity detonated, and the number of bombs 4, 5, and 6 will no more than that of bomb 3.\n**so the looped bomb list should be keeping removing all the sub-detonated bombs after each iteration.**\n\n Please leave messages if you get any questions or suggestions. Thank you.\n\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n \n \n cnt,n=0,len(bombs)\n ori=set(range(n))\n dic={}\n for i in range(n):\n dic[i]=set()\n \n for i in range(n):\n [x1,y1,r1]=bombs[i]\n for j in range(i+1,n):\n [x2,y2,r2]=bombs[j]\n \n sqare_distance=pow(x1-x2,2)+pow(y1-y2,2) \n if sqare_distance<=pow(r1,2):\n dic[i].add(j)\n if sqare_distance<=pow(r2,2):\n dic[j].add(i)\n \n while ori:\n i=ori.pop()\n cur=diff=dic[i] \n cur.add(i)\n pre=cur \n \n while diff: \n for next in diff:\n cur=cur|dic[next] \n \n diff=cur-pre\n pre=cur \n \n ori-=pre // step 3 \n cnt=max(cnt,len(cur))\n \n return cnt
4
0
['Breadth-First Search', 'Python']
1
detonate-the-maximum-bombs
Simple Java DFS [Faster than 90%]
simple-java-dfs-faster-than-90-by-here-c-qel7
Here is a brute force solution. TC might be improved. \n\nThis below snippet code improves the runtime to 90%\n\n\nif(k == bombs.length){ //improves runtime.\n
here-comes-the-g
NORMAL
2021-12-11T16:49:58.928247+00:00
2022-01-10T07:45:58.127174+00:00
429
false
Here is a brute force solution. TC might be improved. \n\nThis below snippet code improves the runtime to 90%\n\n```\nif(k == bombs.length){ //improves runtime.\n return k;\n }\n```\n\n```\nclass Solution {\n Map<Integer, List<Integer>> map = new HashMap<>();\n public int maximumDetonation(int[][] bombs) {\n \n for(int i=0; i<bombs.length; i++){\n int[] b1 = bombs[i];\n for(int j=0; j<bombs.length; j++){\n if(i == j){\n continue;\n }\n int[] b2 = bombs[j];\n if(isInside(b1[0], b1[1], b1[2], b2[0], b2[1])){\n map.putIfAbsent(i, new ArrayList<>());\n map.get(i).add(j);\n }\n }\n }\n\n int max = 0;\n for(int i=0; i<bombs.length; i++){\n int k = dfs(i, new boolean[bombs.length]);\n if(k == bombs.length){ //improves runtime.\n return k;\n }\n max = Math.max(max, k);\n }\n\n return max;\n }\n \n private int dfs(int node, boolean[] vs){\n if(vs[node]){\n return 0;\n }\n vs[node] = true;\n \n int res = 1;\n for(int nei : map.getOrDefault(node, new ArrayList<>())){\n res += dfs(nei, vs);\n }\n\n return res;\n }\n \n\t//if a circle touches or crosses another circle\'s center then detonating the previos circle will also detonate this circle.\n private boolean isInside(long x1, long y1,\n long rad, long x, long y){\n long dist = ((x - x1) * (x - x1) + (y - y1) * (y - y1));\n long radius = rad * rad;\n \n return radius >= dist;\n }\n}\n```
4
0
[]
0
detonate-the-maximum-bombs
Simple py code explained in detail! || BFS
simple-py-code-explained-in-detail-bfs-b-70cd
Problem Understanding\n\n- This is one of my favourite Math,geometry problem.Let\'s undersatnd the question!\n- They have given a list of list named bombs.It c
arjunprabhakar1910
NORMAL
2024-11-05T13:18:42.670605+00:00
2024-11-05T13:18:42.670642+00:00
335
false
# Problem Understanding\n\n- This is one of my favourite Math,geometry problem.Let\'s undersatnd the question!\n- They have given a *list of list* named `bombs`.It contains it\'s location and radius as `[x,y,r]`.\n- We can detonate any bomb,and find the `maximum` number of bombs which will be detonated.\n- A `bomb` is *triggered* if it is in `radius` of another bombs which is being *exploded*.\n- So this problem can be solved in `BFS` or `DFS`.\n---\n\n\n# Approach:BFS\n<!-- Describe your approach to solving the problem. -->\n# Intuition and explantion:\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The idea is simple,we will use `BFS` to all the *bomb* in `bombs`\n the one with `maximum` number of bombs exploded which is the result of our `BFS` will be our solution.\n- ***WHAT\'S THE PROBLEM?*** How to decide which is in our bomb\'s exlosive radius!\n- The ans to this is not tricky,what I did I stored all the distance from one `bomb` to another `bomb` in `distance` matrix of size `l*l`,where `l` is the no of `bombs`.\n- let\'s talk how I did by `BFS` before talking how *eplosion* logic works.while calling `BFS` I required only which bomb I am exploding which is `i` and the `radius-->bombs[i][-1]`.In the queue I stored the same as *tuple*!\n- `visited` stores no of `bombs` which got exploded.\n- The bomb explodes only when the `r` radius of the current bomb which is `idx` is greater than the distance between the `two` bombs\n`i` and `idx` which is calculated from `distance` matrix.\n- `countMax` stores the maximum no of bombs detonated which is calculated by counting no of `visited` in `BFS`.\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```python3 []\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n def distanceCal(x1,y1,x2,y2):\n return math.sqrt((x2-x1)**2+(y2-y1)**2)\n def display(mat):\n for row in mat:\n print(row)\n print(\'-------------------\')\n #BFS\n def BFS(r,i):\n l=len(bombs)\n visited=[False]*l\n visited[i]=True\n q=deque([(r,i)])\n while q:\n l=len(q)\n r,idx=q.popleft()\n for i in range(len(bombs)):\n if not visited[i] and r-distance[idx][i]>=0:\n q.append((bombs[i][-1],i))\n visited[i]=True\n return visited.count(True)\n #distance calculation!\n l=len(bombs)\n distance=[[0]*l for _ in range(l)]\n display(distance)\n for i in range(l):\n for j in range(l):\n distance[i][j]=distanceCal(bombs[i][0],bombs[i][1],bombs[j][0],bombs[j][1])\n display(distance)\n #logic\n countMax=1\n for i in range(len(bombs)):\n countMax=max(countMax,BFS(bombs[i][-1],i))\n return countMax\n\n```\n\n---\n\n\n##### PS:I solved this in `22:03`minutes!
3
0
['Array', 'Math', 'Breadth-First Search', 'Graph', 'Geometry', 'Python3']
0
detonate-the-maximum-bombs
explaination for why union find not working
explaination-for-why-union-find-not-work-poel
Detonation condition is NOT intersection\n2. 1. BUT intersection should include co-ordinate of other bomb range\n2. UNION FIND WILL GIVE FALSE ANSWER FOR BELOW
youngsam
NORMAL
2024-03-26T01:48:55.540321+00:00
2024-03-26T01:48:55.540367+00:00
51
false
**Detonation condition is NOT intersection\n2. 1. BUT intersection should include co-ordinate of other bomb range\n2. UNION FIND WILL GIVE FALSE ANSWER FOR BELOW CASE**\ngiven A(0,0,5) B (4,0,1) C)(9,0,5)\n\n![image](https://assets.leetcode.com/users/images/d918d62e-b7ff-43e7-be94-2ee3a2f84c7c_1711417630.7414768.png)\n\n\nHence Do BFS or (DFS)\nBFS code java\n```\npublic int maximumDetonation(int[][] bombs) { \n int n=bombs.length; \n int max=0; \n for(int i=0;i<n;i++){ \n \n int count=0;\n boolean[] visit=new boolean[n];\n Queue<Integer> q = new LinkedList<>();\n q.offer(i); \n \n while(!q.isEmpty()){\n int u=q.poll();\n visit[u]=true;\n count++;\n \n for(int v=0;v<n;v++){\n if(u==v||visit[v])\n continue;\n\n if(test(u,v,bombs)){\n visit[v]=true;\n q.offer(v);\n } \n }\n } \n \n max=Math.max(max,count);\n }\n \n return max; \n \n }\n \n private boolean test(int i,int j,int[][] bombs){\n int[] b1=bombs[i],b2=bombs[j];\n long x1=b1[0],y1=b1[1],r1=b1[2];\n long x2=b2[0],y2=b2[1],r2=b2[2];\n \n return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)<=r1*r1;\n \n }\n\n\n```\n
3
0
['Breadth-First Search', 'Graph']
0
detonate-the-maximum-bombs
Java | BFS | Beats > 99.7% | With Comments
java-bfs-beats-997-with-comments-by-thar-h5x7
Intuition\n Describe your first thoughts on how to solve this problem. \nWe systematically explore each bomb and its surrounding bombs to determine the maximum
tharunstk2003
NORMAL
2023-06-03T03:25:25.967716+00:00
2023-06-03T03:25:25.967754+00:00
617
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe systematically explore each bomb and its surrounding bombs to determine the maximum number of bombs that can be detonated from each starting point. By performing BFS, we ensure that we consider all reachable bombs and maximize the count of detonations.\n\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n# Here\'s a step-by-step approach:\n\n1.The **isPossible** **function** determines whether a given bomb can detonate another bomb based on their positions and explosion ranges. It calculates the Euclidean distance between the bombs and compares it with the explosion range. If the distance is less than or equal to the explosion range, the bomb can detonate the other bomb.\n2.The **helper function** takes the array of bombs and a current bomb index as input. It iterates through all the other bombs, excluding the current bomb, and checks if the current bomb can detonate the surrounding bomb using the isPossible function. If it can, the index of the surrounding bomb is added to the indi_lst ArrayList.\n3.The **bfs function** performs a BFS traversal starting from a given bomb index. It initializes a queue and a visited array. It adds the starting bomb index to the queue, marks it as visited, increments the count, and then continues exploring its neighboring bombs. For each neighboring bomb, if it hasn\'t been visited yet, it adds it to the queue, marks it as visited, and increments the count. This process continues until the queue is empty.\n4.The **maximumDetonation function** is the main function that utilizes the helper and bfs functions. It iterates through each bomb in the given array. If a bomb has not been visited yet, it calls the bfs function to find the maximum number of bombs that can be detonated starting from that bomb. It keeps track of the maximum count of detonations across all bombs and returns it as the result.\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)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport java.util.*;\n\nclass Solution {\n //Function to know cur_bomb can explode the sur_bomb(current bomb, surounding bomb)\n public static boolean isPossible(int[] cur_bomb, int[] sur_bomb) {\n long cbx = cur_bomb[0];\n long cby = cur_bomb[1];\n long cbcap = cur_bomb[2];\n long sbx = sur_bomb[0];\n long sby = sur_bomb[1];\n return (cbx - sbx) * (cbx - sbx) + (cby - sby) * (cby - sby) <= cbcap*cbcap;\n }\n //helper function to get the ArrayList of surrounding bombs the current bomb can effect.\n public static ArrayList<Integer> helper(int[][] bombs, int cur) {\n ArrayList<Integer> indi_lst = new ArrayList<>();\n for (int i = 0; i < bombs.length; i++) {\n if (i == cur) {\n continue;\n }\n if (isPossible(bombs[cur], bombs[i])) {\n indi_lst.add(i);\n }\n }\n return indi_lst;\n }\n //bfs to find the maximum number of bombs the current bomb can explode.\n public static int bfs(ArrayList<ArrayList<Integer>> lst, int i, boolean[] flag) {\n int res = 0;\n Queue<Integer> que = new LinkedList<>();\n boolean[] cur_vis = new boolean[lst.size()];\n que.add(i);\n flag[i] = true;\n cur_vis[i]=true;\n res++;\n while (!que.isEmpty()) {\n int bmb = que.poll();\n for (int tmp : lst.get(bmb)) {\n if (!cur_vis[tmp]) {\n que.add(tmp);\n res++;\n cur_vis[tmp] = true;\n flag[tmp] = true;\n }\n }\n }\n return res;\n }\n //main function\n public int maximumDetonation(int[][] bombs) {\n int n = bombs.length;\n ArrayList<ArrayList<Integer>> lst = new ArrayList<>(n);\n for (int i = 0; i < n; i++) {\n lst.add(helper(bombs, i));\n }\n int res = 0;\n boolean[] flag = new boolean[n];\n for (int i = 0; i < n; i++) {\n if (!flag[i]) {\n res = Math.max(res, bfs(lst, i, flag));\n }\n }\n // System.out.println(lst);\n return res;\n }\n}\n```
3
0
['Breadth-First Search', 'Java']
2
detonate-the-maximum-bombs
An Easy DFS solution approach || C++
an-easy-dfs-solution-approach-c-by-sazzy-g8zv
Intuition\n Describe your first thoughts on how to solve this problem. \nIf one bomb explodes and the bombs that comes inside its range, it\'s the indication th
sazzysaturn
NORMAL
2023-06-02T19:25:28.941478+00:00
2023-06-02T19:25:28.941515+00:00
304
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf one bomb explodes and the bombs that comes inside its range, it\'s the indication that its a dfs/bfs problem\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere, i have discussed the dfs approach, just running dfs for each bomb (with a new visited array each time) to see how many bombs will explode if that bomb explodes, and then take max out of all.\nI have set the ans initially to one, cause in the worst case 1 bomb will always explode as given in question\n\n# Complexity\n- Time complexity: O(n^2), In the worst case for all dfs calls all bombs will be visited\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n- n = no. of bombs\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\npublic:\n int dfs(vector<vector<int>>& bombs, int i, vector<int>& visited){\n int n = bombs.size();\n visited[i]=1;\n // return 1 + dfs call to the bombs in ranges if not visited\n\n int output = 1;\n for(int j=0;j<n;j++){\n double tot_dist = sqrt(pow(bombs[i][0]-bombs[j][0],2) + pow(bombs[i][1]-bombs[j][1],2));\n if(visited[j]==0 && tot_dist<=bombs[i][2]){\n output+= dfs(bombs,j,visited);\n }\n }\n return output;\n }\n\n int maximumDetonation(vector<vector<int>>& bombs) {\n // I guess my approach after thinking would be a dfs approach, if a bomb denotes dfs to the bomb in its ranges and return the max output out of all dfs calls\n int n = bombs.size();\n \n int ans = 1;\n for(int i=0;i<n;i++){\n vector<int> visited(n,0);\n ans = max(ans,dfs(bombs,i,visited));\n }\n return ans;\n }\n};\n```
3
0
['Array', 'Depth-First Search', 'Breadth-First Search', 'C++']
0
detonate-the-maximum-bombs
Solution in C++
solution-in-c-by-ashish_madhup-hrsn
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
ashish_madhup
NORMAL
2023-06-02T15:25:25.508009+00:00
2023-06-02T15:25:25.508053+00:00
41
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 #define ll long long\n void dfs(int src,vector<int>& vis,vector<int> adj[])\n {\n vis[src]=1;\n for(int x:adj[src])\n {\n if(vis[x]==0)\n {\n dfs(x,vis,adj);\n }\n }\n }\n int maximumDetonation(vector<vector<int>>& bombs) \n {\n int n=bombs.size();\n vector<int> adj[n];\n for(int i=0;i<n;i++)\n {\n ll r1=bombs[i][2];\n ll x1=bombs[i][0];\n ll y1=bombs[i][1];\n for(int j=0;j<n;j++)\n {\n if(i!=j)\n {\n ll x2=bombs[j][0];\n ll y2=bombs[j][1];\n ll r2=bombs[j][2];\n ll dsq=(x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);;\n if(dsq<=r1*r1)\n {\n adj[i].push_back(j); \n }\n }\n }\n }\n vector<int> vis(n);\n int ans=0;\n for(int i=0;i<n;i++)\n {\n dfs(i,vis,adj); \n int cnt=0;\n for(int j=0;j<n;j++) \n if(vis[j]==1) cnt++;\n ans=max(ans,cnt);\n fill(vis.begin(),vis.end(),0);\n }\n return ans;\n }\n};\n```
3
0
['C++']
0
detonate-the-maximum-bombs
✅ 🔥 Python3 || ⚡easy solution
python3-easy-solution-by-maary-ckyy
Code\n\nfrom typing import List\nimport collections\n\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n n2nxt = collect
maary_
NORMAL
2023-06-02T14:42:53.671752+00:00
2023-06-02T14:42:53.671793+00:00
1,237
false
# Code\n```\nfrom typing import List\nimport collections\n\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n n2nxt = collections.defaultdict(set)\n lb = len(bombs)\n\n for i in range(lb): # i is the source\n xi, yi, ri = bombs[i]\n\n for j in range(lb):\n if i == j:\n continue\n\n xj, yj, rj = bombs[j]\n\n if ri ** 2 >= (xi - xj) ** 2 + (yi - yj) ** 2: # reachable from i\n n2nxt[i].add(j)\n\n def dfs(n, seen): # return None\n if n in seen:\n return\n seen.add(n)\n for nxt in n2nxt[n]:\n dfs(nxt, seen)\n\n ans = 0\n for i in range(lb):\n seen = set()\n dfs(i, seen)\n ans = max(ans, len(seen))\n return ans\n\n```
3
0
['Python3']
0
detonate-the-maximum-bombs
C++ || EASY TO UNDERSTAND || DFS
c-easy-to-understand-dfs-by-chicken_rice-nld2
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
chicken_rice
NORMAL
2023-06-02T10:52:57.338694+00:00
2023-06-02T10:52:57.338736+00:00
255
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\n void dfs(int node, int &count, vector<vector<int>> &adj, vector<int> &visited){\n visited[node] = true;\n count++;\n for(auto neigh:adj[node]){\n if(!visited[neigh])\n dfs(neigh, count, adj, visited);\n }\n }\n\n int maximumDetonation(vector<vector<int>>& bombs) {\n int n = bombs.size();\n vector<vector<int>> adj(n);\n\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 if(i != j && (long)ri * ri >= (long)(xi - xj) * (xi - xj) + (long)(yi - yj) * (yi - yj) ){\n adj[i].push_back(j);\n }\n }\n }\n\n \n int ans = -1;\n\n for(int i=0;i<n;i++){\n int count = 0;\n vector<int> visited(n, 0);\n dfs(i, count, adj, visited);\n ans = max(ans, count);\n }\n\n\n return ans;\n }\n};\n```
3
0
['C++']
1
detonate-the-maximum-bombs
🏆 Detailed Explanation 🏆 ( DFS ) with time and space complexity analysis.
detailed-explanation-dfs-with-time-and-s-l8pz
Approach\n Describe your approach to solving the problem. \nBasic idea is to solve this problem is we are considering n bombs from 0 to n-1. We treat this indiv
malav_mevada
NORMAL
2023-06-02T10:43:37.002326+00:00
2023-06-02T10:43:37.002368+00:00
619
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nBasic idea is to solve this problem is we are considering n bombs from 0 to n-1. We treat this individuals bomb as node in the graph. If a bomb can reach to the other bombs it means if bomb radius can cover any other bomb then there should be directed edge between this bombs. We need to do this for each bomb and we created graph.\n\nNow the next question is how do we know that one bomb can cover the other bomn in it radius. So for two bomb if we want to find distance we use this equation:\n$$ d = \\sqrt{(x_2 - x_1)^2 + (y_2-y_1)^2}$$\n\nwe need to check that if distance is less then the radius of bomb then it can reach to the other bomb.\n\n$$\nd<=r,\n$$\n$$\nd^2 = (x_2 - x_1)^2 + (y_2-y_1)^2\n$$\n$$\nd^2 <= r^2 \n$$ if this condition is true it means bombs can detonate other bomb.\n\n# Code\n```\nclass Solution {\n public int maximumDetonation(int[][] bombs) {\n int n = bombs.length;\n\n // Create the adjacency list representation of the graph\n List<List<Integer>> adjList = createGraph(bombs);\n\n // Array to track visited nodes during DFS\n boolean[] vis = new boolean[n];\n\n // Array to keep track of the detonation count\n int[] count = new int[1];\n\n // Variable to store the maximum detonation count\n int maxValue = Integer.MIN_VALUE;\n\n // Perform DFS starting from each node to find the detonation count\n for(int node = 0; node < n; node++){\n Arrays.fill(vis, false); // Reset the visited array for each DFS\n count[0] = 0; // Reset the detonation count for each DFS\n dfs(node, adjList, vis, count); // Perform DFS\n maxValue = Math.max(maxValue, count[0]); // Update the maximum detonation count\n }\n\n return maxValue; // Return the maximum detonation count\n }\n\n // Depth-First Search (DFS) implementation\n public void dfs(int node, List<List<Integer>> adjList, boolean[] vis, int count[]){\n vis[node] = true; // Mark the current node as visited\n count[0]++; // Increment the detonation count for the current node\n\n // Iterate through the adjacent nodes of the current node\n for(Integer adjNode : adjList.get(node)){\n if(!vis[adjNode]){ // If the adjacent node is not visited\n dfs(adjNode, adjList, vis, count); // Recursively perform DFS on the adjacent node\n }\n }\n }\n\n // Create the adjacency list representation of the graph\n public List<List<Integer>> createGraph(int[][] bombs){\n int n = bombs.length;\n List<List<Integer>> adjList = new ArrayList<>(n);\n\n // Iterate through each node in the graph\n for(int node = 0; node < n; node++){\n adjList.add(new ArrayList<>()); // Create an empty list for the current node\n long x1 = bombs[node][0]; // x-coordinate of the current node\n long y1 = bombs[node][1]; // y-coordinate of the current node\n long r1 = bombs[node][2]; // radius of the current node\n\n // Iterate through each other node in the graph\n for(int otherNode = 0; otherNode < n; otherNode++){\n if(node != otherNode){ // If the other node is not the current node\n long x2 = bombs[otherNode][0]; // x-coordinate of the other node\n long y2 = bombs[otherNode][1]; // y-coordinate of the other node\n\n long X = Math.abs(x1 - x2); // Absolute difference in x-coordinates\n long Y = Math.abs(y1 - y2); // Absolute difference in y-coordinates\n\n if(X * X + Y * Y <= r1 * r1){ // If the distance between the nodes is within the radius\n adjList.get(node).add(otherNode); // Add the other node to the adjacency list of the current node\n }\n }\n }\n }\n\n return adjList; // Return the adjacency list\n }\n}\n\n```\n\n# Complexity\n### Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- The **createGraph** method iterates over each bomb and compares it to every other bomb to see if it is within the explosion radius, creating the adjacency list. Due to the two nested loops involved, O(N^2) comparisons are produced. As a result, the adjacency list generation takes O(N^2) time, where N is the total number of bombs.\n\n- **DFS traversal:** For each bomb in the graph, we do a DFS traversal in the main maximumDetonation procedure. We just make one trip to each node during each traverse. The total number of iterations required for the DFS traversal is O(N) since each node can have a maximum of N-1 connections (apart from those to itself).\n\n- Therefore, the overall time complexity of the solution is O(N^2 + N^2), which simplifies to **O(N^2)**.\n\n### Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- The number of bombs, N, determines the solution\'s O(N) space complexity. This is because the connections between each bomb must be stored because we describe the graph as an adjacency list. The area needed would be inversely correlated to the number of explosives in the worst-case scenario, when all bombs are connected to one another.\n\n## Please upvote if you find it useful.\n\nif anything wrong please feel free to comment down.
3
0
['Array', 'Math', 'Depth-First Search', 'Graph', 'Java']
3
detonate-the-maximum-bombs
Simple solution using Java : DFS
simple-solution-using-java-dfs-by-niketh-7yfi
The algorithm is pretty simple \n- First of all you need to create a graph such that it stores the bombs which are located in its range. We have the radius of t
niketh_1234
NORMAL
2023-06-02T08:31:11.295761+00:00
2023-06-02T08:31:11.295801+00:00
295
false
# The algorithm is pretty simple \n- First of all you need to create a graph such that it stores the bombs which are located in its range. We have the radius of the bomb and we run a for loop iterating over all the bombs calculate the distance between the two bombs and compare with the radius then we will able to decide whether the bomb is in our range or not.\n- After creating the graph we need to run DFS/BFS algorithm on the graph and find the total no.of reachable nodes from a particular node. We need to run this for all the nodes present in the graph.\n- The DFS/BFS algorithm count all the reachable nodes and returns the value. We store our result in a varaible called \'result\' and compare it with the newly arrived DFS count.\n- It is a very simple problem , if you are able to write functions for different parts of the problem like Creation of graph and DFS/BFS function.\n\n---\n\n\n\n# Code\n```\nclass Solution {\n public int DFS(HashMap<Integer,ArrayList<Integer>> adj , int source,boolean[] visited)\n {\n visited[source] = true;\n int res = 1;\n for(int item : adj.get(source))\n {\n if(visited[item] == false)\n {\n res += DFS(adj,item,visited);\n }\n }\n return res;\n }\n public int maximumDetonation(int[][] bombs) {\n HashMap<Integer,ArrayList<Integer>> hmap = new HashMap<>();\n for(int i = 0;i<bombs.length;i++)\n {\n ArrayList<Integer> arr = new ArrayList<>();\n hmap.put(i,arr);\n }\n for(int i = 0;i<bombs.length;i++)\n {\n long x1 = bombs[i][0];\n long y1 = bombs[i][1];\n long r1 = bombs[i][2];\n for(int j = 0;j<bombs.length;j++)\n {\n if(i!=j)\n {\n long x2 = bombs[j][0];\n long y2 = bombs[j][1];\n if(((x2-x1)*(x2-x1)) + ((y2-y1)*(y2-y1)) <= r1*r1)\n {\n ArrayList<Integer> arr = hmap.get(i);\n arr.add(j);\n hmap.put(i,arr);\n } \n } \n }\n }\n int result = 1;\n for(int i = 0;i<bombs.length;i++)\n {\n boolean[] visited = new boolean[bombs.length];\n result = Math.max(result,DFS(hmap,i,visited));\n }\n return result;\n }\n}\n```\n\n---\n\n\n#### *If you\'ve liked my explanation don\'t forget to upvote and encourage.*
3
0
['Depth-First Search', 'Breadth-First Search', 'Graph', 'C++', 'Java']
0
detonate-the-maximum-bombs
Detonate the Maximum Bombs | Optimized Solution | Daily Leetcode Challenge
detonate-the-maximum-bombs-optimized-sol-z4wf
\nclass Solution {\npublic:\n // Helper function to calculate distance between two points\n int distance(int x, int y, int x1, int y1)\n {\n dou
aditigulati
NORMAL
2023-06-02T08:29:20.859177+00:00
2023-06-02T08:29:20.859218+00:00
39
false
```\nclass Solution {\npublic:\n // Helper function to calculate distance between two points\n int distance(int x, int y, int x1, int y1)\n {\n double temp = sqrt(pow(x1 - x, 2) + pow(y1 - y, 2)); // Euclidean distance formula\n return ceil(temp); // Round up the distance to the nearest integer\n }\n \n // Depth-first search to calculate the number of bombs that can be detonated starting from a given index\n int dfs(int index, vector<int>& visited, vector<vector<int>>& graph)\n {\n int temp = 1; // Initialize the count to 1, considering the current bomb itself as detonated\n visited[index] = 1; // Mark the current index as visited\n \n // Iterate through the adjacent bombs in the graph\n for (auto x : graph[index])\n {\n if (visited[x] == 0) // If the adjacent bomb has not been visited\n {\n temp += dfs(x, visited, graph); // Recursively calculate the count of detonated bombs\n }\n }\n \n return temp; // Return the total count of detonated bombs\n }\n \n int maximumDetonation(vector<vector<int>>& bombs) {\n int n = bombs.size(); // Total number of bombs\n \n // Create a graph to represent the relationships between bombs\n vector<vector<int>> graph(n);\n \n // Construct the graph by checking the distances between each pair of bombs\n for (int i = 0; i < n; i++)\n {\n for (int j = i + 1; j < n; j++)\n {\n int x = bombs[i][0];\n int y = bombs[i][1];\n int x1 = bombs[j][0];\n int y1 = bombs[j][1];\n int r = bombs[i][2];\n int r1 = bombs[j][2];\n \n // Calculate the distance between the bombs and check if they can detonate each other\n int temp = distance(x, y, x1, y1);\n if (temp <= r)\n {\n graph[i].push_back(j); // Add j as an adjacent bomb to i\n }\n if (temp <= r1)\n {\n graph[j].push_back(i); // Add i as an adjacent bomb to j\n }\n }\n }\n \n // Perform depth-first search on each bomb to find the maximum number of detonated bombs\n vector<int> visited; // Keep track of visited bombs\n vector<int> x(n, 0); // Initialize the visited array with zeros\n int ans = 1; // Initialize the maximum count of detonated bombs to 1\n \n // Iterate through each bomb as a starting point for the depth-first search\n for (int i = 0; i < n; i++)\n {\n visited = x; // Reset the visited array for each iteration\n int temp = dfs(i, visited, graph); // Perform depth-first search and get the count\n ans = max(ans, temp); // Update the maximum count if necessary\n }\n \n return ans; // Return the maximum count of detonated bombs\n }\n};\n```\n\n**PLEASE UPVOTE :)**
3
0
['Depth-First Search', 'C']
0
detonate-the-maximum-bombs
C++ DFS/BFS solutions with detonating bomb process beating 90.22%
c-dfsbfs-solutions-with-detonating-bomb-7ksgn
Intuition\n Describe your first thoughts on how to solve this problem. \nThe crucial part is to create the directed graph, i.e. the adjacent list. The bombs are
anwendeng
NORMAL
2023-06-02T07:05:30.247953+00:00
2023-06-04T11:22:00.695507+00:00
2,381
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe crucial part is to create the directed graph, i.e. the adjacent list. The bombs are the the vertice. If bomb[j] is within the bomb range of bomb[i], there is a directed edge from bomb[i] to bomb[j]. Then either of DFS or BFS can be applied for solving this problem.\n\nAccording the radius of bomb range, sort the bombs in descending order. Then create adjacent list according to Euclidean distance fomula:\n$$\nd^2((x, y),(x_j, y_j))=(x-x_j)^2+(y-y_j)^2\\leq r^2 \\qquad(1)\n$$\nwhere $(x, y,r)$ is the info for the detonating bomb[i] and the bomb[j] with coordinates $(x_j, y_j)$ lies within the bomb[i] range. The computation for the inequality needs to use long long int to prevent overflow! But there are many cases that the bomb is closed to the detonating bomb.\n\nSo, we used firstly the easy computing to test whether\n$$\n|x-x_j|+|y-y_j|\\leq r \\qquad(2)\n$$\nif the inequality (2) that\'s fine add j to adj[i], if not then try the inequality (1) for Euclidean distance fomula. It is clear if the inequality (2) is satisfied, then the inequalty (1) is valid since the triangle inequality.\n[DFS& BFS solves Leetcode 934 shortest bridge with English subtitles, please turn on if necessary]\n[https://youtu.be/9Lx7yr-tmfI](https://youtu.be/9Lx7yr-tmfI)\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTest case:\n```\n[[647,457,91],[483,716,37],[426,119,35],[355,588,40],[850,874,49],[232,568,46],[886,1,30],[54,377,3],[933,986,50],[305,790,49],[372,961,67],[671,314,58],[577,221,29],[380,147,91],[600,535,1],[806,329,64],[536,753,18],[906,88,23],[436,783,82],[652,674,45],[449,668,20],[419,13,66],[853,767,60],[169,288,33],[871,608,66],[337,445,35],[388,623,39],[723,503,81],[14,19,19],[98,648,72],[147,565,93],[655,434,1],[407,663,22],[805,947,83],[942,160,70],[959,496,93],[30,988,53],[187,849,60],[980,483,41],[663,150,76],[268,39,50],[513,522,75],[61,450,90],[115,231,12],[346,304,74],[385,540,23],[905,178,19],[336,896,81],[751,811,94],[527,783,78],[635,965,19],[334,290,39],[748,460,77],[414,134,22],[955,485,29],[925,787,43],[243,771,75],[675,223,29],[788,618,82],[462,544,30],[999,259,50],[210,146,12],[789,442,70],[286,36,55],[451,953,6],[719,914,14],[664,452,14],[933,637,29],[206,926,16],[100,422,98],[97,333,4],[505,631,26],[908,287,65],[907,316,86],[949,185,16],[639,735,62],[401,739,18],[605,926,21],[25,391,69],[80,24,9],[435,874,92],[940,381,18],[260,740,87],[727,515,17],[361,152,16],[512,470,67],[189,27,27],[517,439,94],[159,543,76],[373,698,38],[781,836,97],[584,190,23],[383,367,86],[825,141,63],[117,926,85],[169,588,60],[56,981,100],[294,716,100],[781,370,89],[373,44,78]]\n```\nSort the bombs! Create the adjacent list\n```\nn=100\n56,981,100\n294,716,100\n100,422,98\n781,836,97\n751,811,94\n517,439,94\n147,565,93\n959,496,93\n435,874,92\n647,457,91\n380,147,91\n61,450,90\n781,370,89\n260,740,87\n383,367,86\n907,316,86\n117,926,85\n805,947,83\n436,783,82\n788,618,82\n336,896,81\n723,503,81\n527,783,78\n373,44,78\n748,460,77\n159,543,76\n663,150,76\n243,771,75\n513,522,75\n346,304,74\n98,648,72\n789,442,70\n942,160,70\n25,391,69\n372,961,67\n512,470,67\n871,608,66\n419,13,66\n908,287,65\n806,329,64\n825,141,63\n639,735,62\n187,849,60\n853,767,60\n169,588,60\n671,314,58\n286,36,55\n30,988,53\n933,986,50\n999,259,50\n268,39,50\n850,874,49\n305,790,49\n232,568,46\n652,674,45\n925,787,43\n980,483,41\n355,588,40\n388,623,39\n334,290,39\n373,698,38\n483,716,37\n337,445,35\n426,119,35\n169,288,33\n462,544,30\n886,1,30\n933,637,29\n955,485,29\n675,223,29\n577,221,29\n189,27,27\n505,631,26\n385,540,23\n584,190,23\n906,88,23\n407,663,22\n414,134,22\n605,926,21\n449,668,20\n635,965,19\n905,178,19\n14,19,19\n536,753,18\n401,739,18\n940,381,18\n727,515,17\n206,926,16\n949,185,16\n361,152,16\n719,914,14\n664,452,14\n115,231,12\n210,146,12\n80,24,9\n451,953,6\n97,333,4\n54,377,3\n600,535,1\n655,434,1\n=======\nadj lists:\n0:[16,47]\n1:[13,27,52,60]\n2:[11,33,96,97]\n3:[4,51]\n4:[3]\n5:[28,35]\n6:[25,44,53]\n7:[56,68]\n8:[18,95]\n9:[21,91,99]\n10:[63,77,89]\n11:[2,33,97]\n12:[31,39]\n13:[1,27,52]\n14:[29]\n15:[38,85]\n16:[0]\n18:[61,84]\n20:[34]\n21:[24,86,91]\n22:[83]\n23:[37]\n24:[21,31,86]\n25:[6,44]\n26:[69]\n27:[13,52]\n28:[35,65]\n29:[14,59]\n31:[24]\n32:[81,88]\n33:[97]\n35:[5,28]\n37:[23]\n38:[15]\n39:[12]\n44:[6,25]\n46:[50]\n47:[0]\n50:[46]\n56:[7,68]\n59:[29]\n63:[77]\n68:[7,56]\n77:[63]\n86:[21]\nans=7\n```\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 with Explanation in Comments\nIf the sorting process is not used, the elapsed time is 90 ms and beats 90.22%. With sorting, the elapsed time is 106 ms and beats 81.1%\n```\nclass Solution {\npublic:\n int n;\n int MaxBomb = 1;\n vector<vector<int>> adj;\n\n // Print the information of bombs\n void print(vector<vector<int>>& bombs){\n cout << "n=" << n << endl;\n for(vector<int> b : bombs)\n cout << b[0] << "," << b[1] << "," << b[2] << endl;\n }\n\n // Print the adjacent list information\n void print_adj(){\n cout << "=======\\nadj lists:\\n";\n for(int i=0; i<n; i++){\n cout << i << ":[";\n for(int j=0; j<adj[i].size(); j++)\n cout << adj[i][j] << ",";\n cout << "]" << endl;\n }\n }\n\n // Create the adjacent list\n void create_adj(vector<vector<int>>& bombs){\n for(int i=0; i<n; i++){\n long long r = bombs[i][2], x = bombs[i][0], y = bombs[i][1];\n for(int j=0; j<n; j++){\n if(i != j){\n double xd = bombs[j][0] - x, yd = bombs[j][1] - y;\n if (abs(xd) + abs(yd) <= r) \n// If the distance is less than or equal to the radius, it might be very close to bomb[i]\n \n adj[i].push_back(j);\n else if (r*r >= xd*xd + yd*yd) \n// If the distance satisfies condition (1)\n adj[i].push_back(j);\n }\n }\n }\n }\n\n vector<bool> detonated;\n\n // Use Depth-First Search (DFS) recursively to calculate the number of bombs in the detonation range\n void dfs(int i){\n MaxBomb++;\n detonated[i] = 1;\n for(int j : adj[i]){\n if(!detonated[j])\n dfs(j);\n }\n }\n\n int maximumDetonation(vector<vector<int>>& bombs) {\n n = bombs.size();\n\n // Sort the bombs in descending order based on the radius\n sort(bombs.begin(), bombs.end(),\n [](vector<int>& a, vector<int>& b ){\n if(a[2] != b[2]) return a[2] > b[2];\n return a[1] > b[1];\n });\n\n // Print the sorted bombs information\n print(bombs);\n\n adj.resize(n);\n create_adj(bombs); // Create the adjacent list\n print_adj(); // Print the adjacent list information\n\n int ans = 0;\n detonated.assign(n, 0);\n for(int i = 0; i < n; i++){\n if(!detonated[i]){\n MaxBomb = 0;\n dfs(i); // Call the DFS function to calculate the number of bombs in the detonation range\n ans = max(ans, MaxBomb);\n }\n detonated.assign(n, 0);\n }\n cout << ans << endl;\n return ans;\n }\n};\n\n```\n# BFS can work too. Just replace dfs by bfs\n```\nvoid bfs(int i) {\n queue<int> q;\n q.push(i);\n detonated[i] = 1; \n while (!q.empty()) {\n int j = q.front();\n q.pop();\n MaxBomb++; \n for (int k : adj[j]) {\n if (!detonated[k]) {\n q.push(k);\n detonated[k] = 1;\n }\n }\n }\n }\n```
3
0
['Depth-First Search', 'Breadth-First Search', 'Graph', 'Geometry', 'C++']
1
detonate-the-maximum-bombs
C++ solution using DFS
c-solution-using-dfs-by-piyusharmap-vxyv
Complexity\n- Time complexity:\nO(n^3)\n\n- Space complexity:\nO(n^2)to store the graph + O(n)for dfs recursion stack\n\n# Code\n\n class Solution {\npublic:\n
piyusharmap
NORMAL
2023-06-02T05:21:51.679546+00:00
2023-06-02T05:23:58.969375+00:00
1,288
false
# Complexity\n- Time complexity:\nO(n^3)\n\n- Space complexity:\nO(n^2)to store the graph + O(n)for dfs recursion stack\n\n# Code\n```\n class Solution {\npublic:\n //general dfs algorithm to find all the connected bombs (you can use bfs as well)\n void dfs(int node, vector<int> &visited, vector<int> adj[], int &cnt){\n visited[node] = 1;\n cnt++;\n\n for(auto neighbour: adj[node]){\n if(!visited[neighbour]){\n dfs(neighbour, visited, adj, cnt);\n }\n }\n }\n\n int maximumDetonation(vector<vector<int>>& bombs) {\n int n = bombs.size();\n vector<int> adj[n];\n\n //make a directed graph of the distance of bombs with one another\n //if the radius of a bomb is greater than the distance with another bomb -> it means there is a directed edge between them\n for(int i=0; i<n; i++){\n long long int x0, y0, r0;\n x0 = bombs[i][0];\n y0 = bombs[i][1];\n r0 = bombs[i][2];\n\n for(int j=0; j<n; j++){\n //if i and j are equal it means both bombs are same so there is no need to check\n if(i != j){\n long long int x, y;\n x = abs(x0 - bombs[j][0]);\n y = abs(y0 - bombs[j][1]);\n\n if(x*x + y*y <= r0*r0){\n adj[i].push_back(j);\n }\n }\n }\n }\n\n //call dfs for every node to see how many bombs are connected with that single bomb\n int ans = INT_MIN;\n for(int i=0; i<n; i++){\n int cnt = 0;\n vector<int> visited(n, 0);\n dfs(i, visited, adj, cnt);\n\n ans = max(ans, cnt);\n }\n\n //return the bomb with maximum number of connected bombs\n return ans;\n }\n};\n```
3
0
['Array', 'Math', 'Depth-First Search', 'Graph', 'C++']
1
detonate-the-maximum-bombs
[ C++ ] [ DFS ]
c-dfs-by-sosuke23-k6qn
Code\n\nstruct Solution {\n int maximumDetonation(vector<vector<int>>& a) {\n int n = (int) a.size();\n vector<vector<int>> g(n);\n for
Sosuke23
NORMAL
2023-06-02T04:44:59.847963+00:00
2023-06-02T04:44:59.848020+00:00
1,918
false
# Code\n```\nstruct Solution {\n int maximumDetonation(vector<vector<int>>& a) {\n int n = (int) a.size();\n vector<vector<int>> g(n);\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (i == j) {\n continue;\n }\n long long dx = a[j][0] - a[i][0];\n long long dy = a[j][1] - a[i][1];\n long long dd = dx * dx + dy * dy;\n if (dd <= 1LL * a[i][2] * a[i][2]) {\n g[i].emplace_back(j);\n }\n }\n }\n int ans = 0;\n for (int r = 0; r < n; r++) {\n vector<int> b(n);\n auto dfs = [&](auto&& self, int v, int p) -> void {\n b[v] = 1;\n for (int to : g[v]) {\n if (to == p || b[to]) {\n continue;\n }\n self(self, to, v);\n }\n };\n dfs(dfs, r, -1);\n ans = max(ans, accumulate(b.begin(), b.end(), 0));\n }\n return ans;\n }\n};\n```
3
0
['Depth-First Search', 'C++']
0
detonate-the-maximum-bombs
Python3 Solution
python3-solution-by-motaharozzaman1996-v8zp
\n\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n graph = [[] for _ in bombs]\n for i, (xi, yi, ri) in enumer
Motaharozzaman1996
NORMAL
2023-06-02T02:25:35.205618+00:00
2023-06-02T02:25:35.205667+00:00
1,377
false
\n```\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n graph = [[] for _ in bombs]\n for i, (xi, yi, ri) in enumerate(bombs): \n for j, (xj, yj, rj) in enumerate(bombs): \n if i < j: \n dist2 = (xi-xj)**2 + (yi-yj)**2\n if dist2 <= ri**2:\n graph[i].append(j)\n if dist2 <= rj**2:\n graph[j].append(i)\n \n def fn(x):\n ans = 1\n seen = {x}\n stack = [x]\n while stack: \n u = stack.pop()\n for v in graph[u]: \n if v not in seen: \n ans += 1\n seen.add(v)\n stack.append(v)\n return ans \n \n return max(fn(x) for x in range(len(bombs)))\n```
3
0
['Python', 'Python3']
0
detonate-the-maximum-bombs
EASY TO UNDERSTAND | C++ | DFS
easy-to-understand-c-dfs-by-romegenix-3nvo
\n\nclass Solution {\npublic:\n int cnt = 0;\n void dfs(vector<int> adj[], vector<int>& v, int i){\n cnt++;\n v[i] = 1;\n for(int x:
romegenix
NORMAL
2023-06-02T00:38:43.300977+00:00
2023-06-02T00:39:37.392516+00:00
378
false
\n```\nclass Solution {\npublic:\n int cnt = 0;\n void dfs(vector<int> adj[], vector<int>& v, int i){\n cnt++;\n v[i] = 1;\n for(int x: adj[i])\n if(!v[x])\n dfs(adj, v, x);\n }\n void makeAdjList(vector<vector<int>>& b, vector<int> adj[]){\n for(int i = 0; i<b.size(); ++i){\n for(int j = 0; j<b.size(); ++j){\n if(i!=j)\n if(pow(b[j][0] - b[i][0], 2) + pow(b[j][1] - b[i][1], 2) - pow(b[i][2],2) <= 0)\n adj[i].push_back(j);\n }\n }\n }\n int maximumDetonation(vector<vector<int>>& b) {\n vector<int> adj[b.size()];\n makeAdjList(b, adj);\n int res = 0;\n for(int i = 0; i<b.size(); ++i){\n vector<int> v(b.size(), 0);\n cnt = 0;\n dfs(adj, v, i);\n res = max(res, cnt);\n }\n return res;\n }\n};\n```
3
0
['Depth-First Search', 'Graph', 'C++']
0
detonate-the-maximum-bombs
C++,BFS Easy to Understand.
cbfs-easy-to-understand-by-bnb_2001-khov
Approach:-For Every Bomb We will Check how many others Bombs Lies inside it and how many Bombs lies inside the bomb which Lies inside Checking Bomb and this wil
bnb_2001
NORMAL
2022-05-04T06:06:56.319634+00:00
2022-05-04T06:06:56.319660+00:00
167
false
**Approach**:-For Every Bomb We will Check how many others Bombs Lies inside it and how many Bombs lies inside the bomb which Lies inside Checking Bomb and this will Go on.\n-->This will be done with the help of **BFS.**\n-->We will return the bomb which will cover Maximum number of Bombs..\n```\n#define ll long long int\nclass Solution {\npublic:\n ll BFS(vector<vector<int>>& bombs,int i)\n {\n vector<bool>visited(bombs.size(),0);\n queue<int>q;\n q.push(i);\n visited[i]=true;\n ll count=1;\n int n=visited.size();\n while(!q.empty())\n {\n int idx=q.front();\n q.pop();\n ll x=bombs[idx][0];\n ll y=bombs[idx][1];\n ll r=bombs[idx][2];\n \n for(int k=0;k<n;k++)\n {\n if(visited[k]==1) continue;\n \n ll x1=bombs[k][0];\n ll y1=bombs[k][1];\n \n ll dist=(x-x1)*(x-x1)+(y-y1)*(y-y1); //Distance btween center.\n \n if(dist<=r*r) //Check whaether it Lies inside it or not (condition that Point Lies inside a circle)\n count++,visited[k]=1,q.push(k); //If yes Mark as Visited ,increase Count and Push in queue.\n }\n }\n \n return count;\n }\n int maximumDetonation(vector<vector<int>>& bombs) {\n ll ans=1,n=bombs.size();\n vector<bool>visited(n,0);\n for(int i=0;i<n;i++)\n {\n /*For every Bomb Check how many Bomb we can detonate.\n -->Use BFS to Check*/\n ans=max(ans,BFS(bombs,i)); \n }\n \n return (int)ans;\n }\n};\n```\n*If you find it helpful, please upvote.*
3
0
['Breadth-First Search']
0
detonate-the-maximum-bombs
Easy c++ solution || DFS
easy-c-solution-dfs-by-thanoschild-jyfc
\nclass Solution {\npublic:\n void dfs(int i, int &count, vector<bool> &visited, vector<vector<int>> &adj){\n visited[i] = true;\n count++;\n
thanoschild
NORMAL
2022-02-13T04:37:24.145672+00:00
2022-02-13T04:37:24.145714+00:00
375
false
```\nclass Solution {\npublic:\n void dfs(int i, int &count, vector<bool> &visited, vector<vector<int>> &adj){\n visited[i] = true;\n count++;\n for(auto it : adj[i])\n {\n if(!visited[it])\n dfs(it, count, visited, adj);\n }\n }\n int maximumDetonation(vector<vector<int>>& bombs) {\n int n = bombs.size();\n vector<vector<int>> adj(n);\n for(int i=0; i<n; i++){\n long long r1 = bombs[i][2];\n long long x1 = bombs[i][0], y1 = bombs[i][1];\n for(int j = 0; j<n; j++){\n if(j != i){\n long long x2 = bombs[j][0], y2 = bombs[j][1];\n long long dist = (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2);\n if(dist <= r1*r1)\n adj[i].push_back(j);\n }\n }\n }\n vector<bool> visited(n, 0);\n int ans = 0;\n for(int i=0; i<n; i++)\n {\n int count = 0;\n dfs(i, count, visited, adj);\n ans = max(ans, count);\n fill(visited.begin(), visited.end(), 0);\n } \n return ans;\n }\n};\n```
3
0
['Depth-First Search', 'Graph', 'C']
0
detonate-the-maximum-bombs
Union Find 146 / 160 test cases passed. Why?
union-find-146-160-test-cases-passed-why-683a
Any buddy give me some advise? Why Union Find does\'t work!\n\n\nclass Union:\n def __init__ (self,n):\n self.root = [i for i in range(n)]\n se
AndrewHou
NORMAL
2021-12-12T22:56:11.506873+00:00
2021-12-12T22:56:11.506903+00:00
947
false
Any buddy give me some advise? Why Union Find does\'t work!\n```\n\nclass Union:\n def __init__ (self,n):\n self.root = [i for i in range(n)]\n self.rank = [1 for i in range(n)]\n self.count = n\n \n def union(self,x,y):\n rootX = self.find(x)\n rootY = self.find(y)\n if rootX != rootY:\n if self.rank[x]>self.rank[y]:\n self.root[rootY] = rootX\n elif self.rank[x]<self.rank[y]:\n self.root[rootX] = rootY\n else:\n self.root[rootY]=rootX\n self.rank[rootX] += 1 \n self.count -= 1\n \n \n def find(self,x):\n if self.root[x]==x:\n return x\n self.root[x]=self.find(self.root[x])\n return self.root[x]\n\n\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n l = len(bombs)\n u = Union(l)\n \n def distance (p1,p2):\n return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5\n \n for i in range(l):\n for j in range(l):\n # if i==j:\n # continue\n di = distance(bombs[i],bombs[j])\n # print(di)\n if bombs[i][2]>=di or bombs[j][2]>=di:\n u.union(i,j)\n\n print(u.root)\n mapping = {}\n for i in u.root:\n mapping[i] = mapping.get(i,0) + 1\n return max(mapping.values())\n\n```
3
0
['Union Find']
2
detonate-the-maximum-bombs
c++(28ms 100%) Hamilton path with BFS
c28ms-100-hamilton-path-with-bfs-by-zx00-7rbr
Runtime: 28 ms, faster than 100.00% of C++ online submissions for Detonate the Maximum Bombs.\nMemory Usage: 20.4 MB, less than 53.85% of C++ online submissions
zx007pi
NORMAL
2021-12-12T07:21:40.505602+00:00
2021-12-12T07:28:53.961417+00:00
145
false
Runtime: 28 ms, faster than 100.00% of C++ online submissions for Detonate the Maximum Bombs.\nMemory Usage: 20.4 MB, less than 53.85% of C++ online submissions for Detonate the Maximum Bombs.\n```\nclass Solution {\npublic:\n int maximumDetonation(vector<vector<int>>& b) {\n int n = b.size(), answer = 1;\n vector<vector<int>>g(n);\n \n for(int i = 0; i != n; i++){\n long R = (long)b[i][2] * b[i][2];\n for(int j = i+1; j != n; j++){\n long dx = b[j][0] - b[i][0], dy = b[j][1] - b[i][1];\n long r = (long)b[j][2] * b[j][2];\n long d = dx*dx + dy*dy;\n if( d <= R) g[i].push_back(j);\n if( d <= r) g[j].push_back(i);\n }\n }\n \n for(int i = 0; i != n && answer != n; i++){\n vector<int>vis;\n vis.clear();\n vis.resize(n,0);\n queue<int>q;\n q.push(i);\n \n int k = 0;\n while(!q.empty()){\n int t = q.front(); q.pop();\n if(vis[t]) continue;\n vis[t] = 1, k++;\n \n for(auto next: g[t]) if(vis[next] == 0) q.push(next);\n }\n answer = max<int>(answer, k);\n }\n \n return answer;\n }\n};\n```\n\n**when I was solving contest I tried to solve this proublem with greedy algo , but it pass only 153 tests from 157 (very pity)**\n```\nclass Solution {\npublic:\n static bool comp(vector<int> &a, vector<int>&b){\n return a[2] > b[2];\n }\n \n int maximumDetonation(vector<vector<int>>& b) {\n sort(b.begin(), b.end(), comp);\n int n = b.size(), answer = 1;\n vector<int>vis(n,0);\n \n for(int i = 0; i != n; i++)\n if(vis[i] == 0){\n vis[i] = 1;\n vector<vector<int>>v;\n v.push_back(b[i]);\n for(int j = 0; j != v.size(); j++){\n long R = (long)v[j][2] * v[j][2]; \n for(int k = 0; k != n; k++)\n if(vis[k] == 0){\n long dx = v[j][0] - b[k][0], dy = v[j][1] - b[k][1];\n if( dx*dx + dy*dy <= R)\n vis[k] = 1, v.push_back(b[k]); \n }\n } \n answer = max<int>(answer, v.size());\n v.clear();\n }\n \n return answer;\n }\n};\n```
3
0
['C', 'C++']
0
detonate-the-maximum-bombs
JavaScript simple BFS explained
javascript-simple-bfs-explained-by-svolk-1d85
For every bomb we build a list of bombs that will detonate if current bomb will detonante.\nStart dfs for every bomb and count how many bombs will finally deton
svolkovichs
NORMAL
2021-12-11T18:29:20.456453+00:00
2021-12-12T10:46:44.066698+00:00
382
false
For every bomb we build a list of bombs that will detonate if current bomb will detonante.\nStart dfs for every bomb and count how many bombs will finally detonate if current bomb will detonate first.\nStore the max achived number of bombs.\n```\nvar maximumDetonation = function(bombs) {\n const n = bombs.length\n let map = new Map()\n\t// For every bomb build list of affected bombs\n for(let i = 0; i < n; i++){\n map.set(i, [])\n for(let j = 0; j < n; j++){\n if(i === j){\n continue\n }\n let b1 = bombs[i]\n let b2 = bombs[j]\n if(willDetonateBomb(b1[0], b1[1], b1[2], b2[0], b2[1], b2[2])){\n const a = map.get(i)\n a.push(j)\n }\n }\n }\n \n let max = 0\n\t// run BFS for every bomb\n for(let i = 0; i < bombs.length; i++){\n const queue = [i]\n const visited = new Set()\n\n while(queue.length){\n let current = queue.shift()\n \n if(!visited.has(current)){\n visited.add(current)\n const ch = map.get(current)\n \n ch.forEach(c => {\n if(!visited.has(c)){\n queue.push(c)\n }\n })\n }\n }\n \n max = Math.max(visited.size, max)\n }\n \n return max\n};\n\nfunction willDetonateBomb(x1, y1, r1,x2, y2, r2)\n{\n let distSq = (x1 - x2) * (x1 - x2) +\n (y1 - y2) * (y1 - y2)\n let radSq = r1 * r1\n if (distSq <= radSq)\n return true\n return false\n}\n\n\n```
3
0
['Breadth-First Search', 'JavaScript']
0
detonate-the-maximum-bombs
[C++] Graph | Thought Process
c-graph-thought-process-by-user1908v-ti9c
Thought Process in Brief: \n\nI thought about the relation between any two bombs. It appeared every (bomb1,bom2) pair can be represented with true/false. i.e do
user1908v
NORMAL
2021-12-11T16:53:57.891341+00:00
2021-12-11T17:27:50.468471+00:00
355
false
Thought Process in Brief: \n\nI thought about the relation between any two bombs. It appeared every (bomb1,bom2) pair can be represented with true/false. i.e does triggering bomb2 triggers bomb1? So I created a matrix with **(i,j)==true**, if: **j**th bomb triggers **i**th bomb\n\nI thought about triggering every one of them one by one. I was initially thinking in the lines of a 1D dp, which was wrong since the problem can\'t be broked down in smaller subproblem with some function f,z such that: f(n)=z(f(n-1)) *[Think about it]*\n\nObserving the relation i.e. the matrix, it appeared as an adjacency matrix, So the problem must be modelable as a graph with ***bombs as nodes*** and the ***relations as directed edges***. \n\nVoila, it is a question of finding the node from which maximum nodes can be traversed in the connected component. (which can be done using dfs) \n\n\n```\nclass Solution {\npublic:\n bool inrange(int x1,int y1,int r1,int x2,int y2,int r2){\n long long int x=abs(x1-x2);\n long long int y=abs(y1-y2);\n long long int r=abs(r2);\n return x*x+y*y<=r*r;\n }\n int maximumDetonation(vector<vector<int>>& bombs) {\n int n=bombs.size();\n vector<vector<bool>> v(n,vector<bool>(n,false));\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++)\n if(inrange(bombs[i][0],bombs[i][1],bombs[i][2],bombs[j][0],bombs[j][1],bombs[j][2]))\n v[i][j]=true;\n }\n int maxi=0;\n for(int i=0;i<n;i++){\n vector<int> visited(n,-1);\n int num=1;\n if(visited[i]==-1) dfs(v,visited,num,i);\n maxi=max(maxi,num);\n }\n return maxi;\n }\n void dfs(vector<vector<bool>>& v,vector<int>& visited,int& num,int cur){\n visited[cur]=num;\n for(int i=0;i<visited.size();i++){\n if(visited[i]==-1 and v[i][cur])\n dfs(v,visited,++num,i);\n }\n }\n};\n```
3
0
['Depth-First Search', 'Graph']
1
detonate-the-maximum-bombs
BFS, C++
bfs-c-by-1mknown-hqos
First make a graph in such a way that there will be a directed edge from u to v if and only if the distance between u and v is less than or equal to the radius
1mknown
NORMAL
2021-12-11T16:14:38.437935+00:00
2021-12-11T16:23:05.381945+00:00
325
false
First make a graph in such a way that there will be a directed edge from u to v if and only if the distance between u and v is less than or equal to the radius of u.\n\nThen do Bfs one by one from each bomb and find the maximum ans.\n\ncode:\n```\nint maximumDetonation(vector<vector<int>>& nums) {\n vector<vector<int>>graph(nums.size(), vector<int>());\n for(int i=0;i<nums.size();i++){\n int cx=nums[i][0], cy=nums[i][1], cr=nums[i][2];\n for(int j=0;j<nums.size();j++){\n if(i!=j){\n int x=nums[j][0], y=nums[j][1];\n long long dis=(long long)pow(abs(cx-x), 2)+(long long)pow(abs(cy-y), 2);\n if(sqrt(dis)<=cr){\n graph[i].push_back(j);\n }\n }\n }\n }\n int ans=0;\n for(int i=0;i<nums.size();i++){\n int cur=0;\n queue<int>q;\n q.push(i);\n unordered_map<int, int>visited;\n visited[i]=1;\n while(!q.empty()){\n int f=q.front();q.pop();\n cur++;\n for(auto v:graph[f]){\n if(visited[v]==0){\n q.push(v);\n visited[v]=1;\n }\n }\n }\n ans=max(ans, cur);\n }\n return ans;\n }\n```
3
0
['Breadth-First Search', 'C']
0
detonate-the-maximum-bombs
Optimal DFS (Detailed Explanation) | 27ms
optimal-dfs-detailed-explanation-27ms-by-5n0z
Explanation\nThis problem can be approached from the perspective of the bombs being associated with each other in a directed manner (i.e. for a pair of bombs i
ttaylor27
NORMAL
2023-11-29T21:21:51.332070+00:00
2023-12-19T20:36:49.350428+00:00
353
false
# Explanation\nThis problem can be approached from the perspective of the bombs being associated with each other in a directed manner (i.e. for a pair of bombs `i` and `j`, there can be a case where bomb `i` can blow up bomb `j`, but bomb `j` cannot blow up bomb `i`, and vice versa). Because of this, the bombs have a 1-way association with each other, which we can then deduce means that the bombs can be represented with a directed graph. We must be careful to realize that it is not guaranteed to be acyclic, as there can also be the case where bomb `i` can blow up bomb `j`, and bomb `j` can also blow up bomb `i`, etc. \n\nSo now we understand how we can represent the problem using a data structure we are familiar with. In my case, we will use an adjancency list where for a bomb `i` we know the neighboring bombs that we can reach (calculated using Squared Euclidean distance compared with blast radius of bomb `i`). \n\nWith our intuition for how the bombs are represented, we can identify that we can calculate the total bombs that will be detonated if we start at any given bomb `i` by performing a DFS, starting at `i`. This is because if we can reach a bomb `j` starting at bomb `i` in our graph, it means that the explosion from bomb `i` will set off bomb `j`. \n\nOf course because the graph is not guaranteed to be acyclic, we need to be sure to avoiding trapping ourselves in a loop (i.e. visiting the same bomb twice). The traditional method for doing so is to keep a `visited` set, and check whether or not we have already visited that bomb using that set before proceeding. Now, one pitfall with our `visited` set is that theoretically we will have to reset it after each iteration, because there is a case where we would have marked a chain of bombs as visited from a non-maximal starting point, meaning that when we attempt to visit that chain of bombs from the maximal starting point, we will not be able to, making our code incorrect for that case. To avoid this, most implementations appear to just reset the `visited` set for each starting bomb, however this can potentially be expensive. Therefore, my way for getting around this is to keep a visited set of type `short`, where the store number represents the starting bomb for which that bomb in `vis` has been visited already. \n\nThis essentially means that we can keep one set throughout the whole DFS, updating the set as we go with the starting bomb\'s index, and checking whether or not the current DFS we are performing originated at that starting index, and if it did not, then we know we have not visited that bomb in this current iteration and we may proceed with our exploration. Doing this is a key optimization, as we avoid having to recreate a set each time we want to start at a bomb. It also means we can skip starting at a bomb that has already been visited before, because we know that if we have visited it in the past, we have already found the maximum bombs that it can detonate from that point. \n\n# Code\n```C++ []\nclass Solution {\npublic:\n typedef long long LL;\n vector<vector<short>> adj;\n vector<short> vis;\n\n // Check if a bomb is in the blast radius of another bomb\n bool inRange(const LL & x1, const LL & x2, const LL & y1, const LL & y2, const LL & r) {\n return ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) <= (r * r);\n }\n\n // Build our graph\n void buildGraph(vector<vector<int>> & bombs) {\n const int LENGTH = bombs.size();\n for (short i = 0; i < LENGTH; i++) {\n for (short j = i + 1; j < LENGTH; j++) {\n if (inRange(bombs[i][0], bombs[j][0], bombs[i][1], bombs[j][1], bombs[i][2])) adj[i].push_back(j);\n if (inRange(bombs[i][0], bombs[j][0], bombs[i][1], bombs[j][1], bombs[j][2])) adj[j].push_back(i);\n }\n }\n }\n\n // Our simple DFS\n // Only complexity is the reuse of the visited set\n int countBombs(vector<vector<int>> & bombs, int bomb, int start) {\n if (vis[bomb] == start) return 0;\n vis[bomb] = start;\n int count = 1;\n for (const auto & i : adj[bomb]) count += countBombs(bombs, i, start);\n return count;\n }\n\n int maximumDetonation(vector<vector<int>>& bombs) {\n const int LENGTH = bombs.size();\n adj.resize(LENGTH);\n vis.resize(LENGTH, -1);\n buildGraph(bombs);\n\n int maxBombs = 0;\n for (short i = 0; i < LENGTH; i++) if (vis[i] == -1) maxBombs = max(maxBombs, countBombs(bombs, i, i));\n return maxBombs;\n }\n};\n```\n
2
0
['Depth-First Search', 'C++']
0
detonate-the-maximum-bombs
[python] Union find *can* work but not in the way your thinking
python-union-find-can-work-but-not-in-th-mjqf
Intuition\nIn order to understand the following I assume you have a strong grasp of union find and the default solution to this problem. \n\nWhy doesnt vanilla
ada8
NORMAL
2023-10-25T00:19:22.739821+00:00
2023-10-29T00:20:33.128578+00:00
214
false
# Intuition\nIn order to understand the following I assume you have a strong grasp of union find and the default solution to this problem. \n\nWhy doesnt vanilla union find work here? Because edges can be directional or bidirectional in this problem. \ni.e If the graph had all bi-directional edges union find would work fine.\n\nBut can we gain some perf by labeling the bidirectional clusters if they exist? \nyes! \n\ni.e \n\nwe use the parent labels to prune our search.\nif we traverse a single node from a connected cluster, there is no point in traversing another node from within that cluster. \n\nIn addition, if we have a bomb chain,\nWe always want to start from the "root" when traversing if possible\nand not re-traverse any child nodes further down the chain. \n\n# Code\n```\nfrom collections import defaultdict \n\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n def is_connected(p1, p2):\n p1x, p1y, p1r = p1\n p2x, p2y, p2r = p2 \n return p1r ** 2 >= (p2y - p1y)**2 + (p2x - p1x)**2\n \n def find(node):\n while node != parent[node]:\n parent[node] = parent[parent[node]]\n node = parent[node]\n return node \n\n \n def union(a, b):\n pa, pb = find(a), find(b)\n if pa == pb:\n return \n if rank[pa] > rank[pb]:\n rank[pa] += rank[pb]\n parent[pb] = pa \n else:\n rank[pb] += rank[pa]\n parent[pa] = pb \n \n def iter_search(root):\n stack = [root]\n visited = set(stack)\n while stack:\n for next_node in graph[stack.pop()]:\n if next_node in visited: continue \n visited.add(next_node)\n stack.append(next_node)\n return len(visited) \n\n parent = list(range(len(bombs)))\n rank = [1] * len(bombs)\n\n graph = defaultdict(list)\n visited = set() \n is_child = set() \n\n for i in range(len(bombs)):\n for j in range(len(bombs)):\n if i == j: continue \n if is_connected(bombs[i], bombs[j]):\n graph[i].append(j)\n if is_connected(bombs[j], bombs[i]):\n # Amortized O(1) op\n union(i, j)\n else:\n # optimization:\n # dont traverse from child nodes\n # if its directional\n is_child.add(j)\n\n\n\n\n maxv = 0 \n for node in range(len(bombs)):\n if parent[node] in visited or node in is_child:\n continue \n maxv = max(maxv, iter_search(node))\n visited.add(parent[node])\n return maxv \n\n```
2
0
['Union Find', 'Graph', 'Biconnected Component', 'Strongly Connected Component', 'Python3']
1
detonate-the-maximum-bombs
C++ Simple DFS Solution
c-simple-dfs-solution-by-h_wan8h-e1ab
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n\n\n# Code\n\nclass S
h_WaN8H_
NORMAL
2023-09-06T04:49:54.939690+00:00
2023-09-06T04:49:54.939709+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n\n# Code\n```\nclass Solution {\npublic:\n void dfs (unordered_map<int,vector<int>>&adj, int u, vector<bool>&visited, int &ans){\n\n visited[u]=true;\n ans++;\n\n for(auto &it : adj[u]){\n if(!visited[it]){\n dfs(adj,it,visited,ans);\n }\n }\n }\n int maximumDetonation(vector<vector<int>>& bombs) {\n \n unordered_map<int,vector<int>> adj;\n \n\n for(int i=0; i<bombs.size(); i++){\n\n int x1 = bombs[i][0];\n int y1 = bombs[i][1];\n int r1 = bombs[i][2];\n\n for(int j=i+1; j<bombs.size(); j++){\n\n int x2 = bombs[j][0];\n int y2 = bombs[j][1];\n int r2 = bombs[j][2];\n\n double dist = pow(pow(x2-x1,2)+pow(y2-y1,2),0.5);\n\n if(dist<=r1){\n adj[i].push_back(j);\n }\n\n if(dist<=r2){\n adj[j].push_back(i);\n }\n }\n }\n\n int ans = 1;\n\n for(int i=0; i<bombs.size(); i++){\n\n int currans = 0;\n vector<bool>visited(bombs.size(),false);\n\n dfs(adj,i,visited,currans);\n ans = max(ans , currans);\n }\n\n return ans;\n }\n};\n```
2
0
['Math', 'Depth-First Search', 'Graph', 'Geometry', 'C++']
0
detonate-the-maximum-bombs
VERY Intuitive SOLUTION!! AMAZING DSA CONCEPTS USED!!! MUST SEE!!!
very-intuitive-solution-amazing-dsa-conc-4lx8
This question deserves more attention as it is one of the most beautiful problems I\'ve seen! Absolute JOY !!\n# Intuition\n Describe your first thoughts on how
iamsuteerth
NORMAL
2023-06-13T20:38:56.519307+00:00
2023-06-13T20:38:56.519323+00:00
55
false
## This question deserves more attention as it is one of the most beautiful problems I\'ve seen! Absolute JOY !!\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNow, the biggest question in anyone\'s mind when they first see this question is "How is this a graph\'s question"? And that\'s where the solution is! Once you figure it out, its just a matter of applying DFS or BFS!!\n\nThe hint is given in the question itself! Now, consider yourself on the first bomb, if there are any other bombs in your blast radius, they will explode when YOU explode! So, isn\'t that similar to you having a path to those bombs?\n\nSimilarly, every bomb will have its own range of other bombs. You will observe a graph like structure getting formed where the paths are basically saying that this bomb can be "reached" or exploded.\nYou just need to find the max depth of the created graph!\n\n## My solution is kind of not very efficient, but it is simple, intuitive, focuses on core DSA concepts and solves the problem gracefully!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCoordinate Geometry distance formula is used to calculate distance between any two points\n\nFirst, you need to create the graph!\n\nFor that, I have used the adjacency list method implemented using an unordered MAP! Where each key is the vertex having a vector of elements which are the nodes it can reach aka the bombs within the blast radius.\n\nTo check if the bomb is in the blast radius, if the sum of radius of the two bombs is greater or equal to the distance between the centers of the bombs, then the said bombs are in blast radius of each other. That\'s exactly what I\'ve done here.\nFor every ith bomb, i check it with all the bombs except for the case where i==j as its comparing the bomb with itself.\n\nI am using a set as my visited tool, mostly for using the size function to get my answer!\nI apply DFS on every "key" of my map or adj. list and keep on taking max of size of visited set as my answer!\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)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n typedef long long LL;\n LL distancesq(LL x1, LL y1, LL x2, LL y2){\n return (LL)((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2));\n }\n int max(int a, int b){\n return a > b ? a : b;\n }\n void dfs(unordered_map<int, vector<int>> &umap, int u,unordered_set<int> & visited){\n visited.insert(u);\n for(int &v : umap[u]){\n if(visited.find(v) == visited.end()){\n dfs(umap, v, visited);\n }\n }\n }\n int maximumDetonation(vector<vector<int>>& bombs) {\n // r >= d for a bomb to detonate other bomb\n unordered_map<int, vector<int>> umap;\n int count = 0;\n int n = bombs.size();\n for(int i = 0 ; i < n ; i++){\n for(int j = 0; j < n ; j++){\n if(i == j)\n continue;\n LL x1 = bombs[i][0];\n LL x2 = bombs[j][0];\n LL y1 = bombs[i][1];\n LL y2 = bombs[j][1];\n LL centre_dist = distancesq(x1, y1, x2, y2);\n LL r = bombs[i][2];\n if ((r * r) >= centre_dist)\n umap[i].push_back(j);\n }\n }\n int m = 0;\n unordered_set<int> visited;\n for(int i = 0; i<n; i++) {\n dfs(umap, i, visited);\n m = max(m, visited.size());\n visited.clear();\n }\n return m;\n }\n};\n```
2
0
['Array', 'Math', 'Depth-First Search', 'Graph', 'C++']
0
detonate-the-maximum-bombs
Easy to understand, Straight forward C++ solution || DFS ✈️✈️✈️✈️✈️✈️✈️
easy-to-understand-straight-forward-c-so-xk2r
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
ajay_1134
NORMAL
2023-06-07T08:26:02.436663+00:00
2023-06-07T08:26:02.436715+00:00
19
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 check(int xi, int yi, int ri, int xj, int yj){\n // return (long)ri * ri >= (long)(xi - xj) * (xi - xj) + (long)(yi - yj) * (yi - yj); \n long long c1c2 = (long long )(xi - xj) * (xi - xj) + (long long)(yi - yj) * (yi - yj);\n long long r1r2 = (long long) ri * ri;\n return r1r2 >= c1c2;\n }\n void dfs(int node, vector<vector<int>>&g, vector<int>&vis, int &cnt){\n cnt++;\n vis[node] = 1;\n for(auto i:g[node]){\n if(!vis[i]) dfs(i,g,vis,cnt);\n }\n }\n int maximumDetonation(vector<vector<int>>& bombs) {\n int n = bombs.size();\n vector<vector<int>>g(n);\n \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 if(i!=j && check(xi,yi,ri,xj,yj)){\n g[i].push_back(j);\n } \n }\n }\n int ans = 0;\n for(int i=0; i<n; i++){\n int cnt = 0;\n vector<int>vis(n,0);\n dfs(i,g,vis,cnt);\n ans = max(ans,cnt);\n }\n return ans;\n }\n};\n```
2
0
['Depth-First Search', 'Graph', 'C++']
0
detonate-the-maximum-bombs
✅ || C++ || Beginner Friendly || Easy to Understand || O(N^3) Time Complexity ||
c-beginner-friendly-easy-to-understand-o-nmlk
Complexity\n- ## Time complexity:\n1. The outer loop iterates N times, where N is the number of bombs (for(long long i=0; i<bombs.size(); i++)).\n\n Time com
ananttater
NORMAL
2023-06-03T07:21:20.787925+00:00
2023-06-03T07:21:20.787969+00:00
23
false
# Complexity\n- ## Time complexity:\n1. The outer loop iterates N times, where N is the number of bombs (for(long long i=0; i<bombs.size(); i++)).\n\n Time complexity: O(N)\n2. Inside the outer loop, there is a while loop that iterates until the stack is empty.\n\n3. The while loop can potentially iterate N times because each bomb can be visited at most once.\nTherefore, the worst-case time complexity of the while loop is O(N).\n4. Inside the while loop, there is an inner loop that iterates N times (for(long long j=0; j<bombs.size(); j++)).\nTime complexity: O(N)\n5. The total time complexity of the inner loop is O(N), and it is executed O(N) times (inside the while loop).\nTime complexity: O(N^2)\n\nPutting it all together, the overall time complexity is O(N) * O(N^2) = O(N^3).\n\n- ## Space complexity:\n1. The maxBombs variable requires constant space.\n\n2. The visited vector is used to track visited bombs. It has a size equal to the number of bombs, so it requires O(N) space.\n\n3. The s stack is used for the DFS traversal. In the worst case, when all bombs are visited, the stack can store N elements.\n\n4. The space complexity of the s stack is O(N).\nAll other variables used within loops require constant space.\n\nPutting it all together, the overall space complexity is dominated by the space used by the visited vector and the s stack, both of which can grow up to N elements. Therefore, the space complexity of your code is O(N^2), where N is the number of bombs.\n\n# Code\n```\nclass Solution {\npublic:\n int maximumDetonation(vector<vector<int>>& bombs) {\n long long maxBombs = 0;\n for(long long i=0; i<bombs.size(); i++) // O(N)\n {\n long long crrIndBombs = 1;\n \n vector<long long> visited(bombs.size(), 0); \n stack<long long> s;\n s.push(i);\n visited[i] = 1;\n\n while(s.size())\n {\n long long node = s.top();\n long long rad = bombs[node][2];\n long long xCord = bombs[node][0];\n long long yCord = bombs[node][1];\n s.pop();\n\n for(long long j=0; j<bombs.size(); j++)\n {\n if(!visited[j])\n {\n long long total = ((xCord - bombs[j][0]) * (xCord - bombs[j][0])) + ((yCord - bombs[j][1]) * (yCord - bombs[j][1]));\n if (sqrt(total) <= rad){\n crrIndBombs++;\n s.push(j);\n visited[j] = 1;\n }\n }\n }\n }\n\n maxBombs = max(maxBombs, crrIndBombs);\n }\n return maxBombs;\n }\n};\n```
2
0
['C++']
0
detonate-the-maximum-bombs
Kosaraju's Algorithm + Topological Sort
kosarajus-algorithm-topological-sort-by-g1ms2
Intuition\n Describe your first thoughts on how to solve this problem. \nThis is an attempt to arrive at an O(n^2) solution by using the concept of Strongly Con
sinclaire
NORMAL
2023-06-03T05:03:41.920738+00:00
2023-06-03T05:03:41.920779+00:00
430
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is an attempt to arrive at an $$O(n^2)$$ solution by using the concept of Strongly Connected Components. This approach still runs at $$O(n^3)$$ time.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) Creation of adjacency list and reversed adjacency list. This costs looping through the vertices twice, therefore this costs $$O(n^2)$$.\n\n2) Kosaraju\'s algorithm. This costs running through the adjacency list twice. The adjacency list can have $$n^2$$ items. Therefore, this costs $$O(n^2)$$.\n\n3) Topological sort in reversed order. We avoid double counting of bombs by using hashset on each node. We update the child hashset when the parent detonates the child. Updating a set with multiple items costs $$O(n)$$. The topological sort algorithm runs through the $$n^2$$ items. Therefore, the total is $$O(n^3)$$.\n\n# Complexity\n- Time complexity: $$O(n^3)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\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 def maximumDetonation(self, bombs: List[List[int]]) -> int:\n # // Adjacency List\n b = [Bomb(x, y, r) for x, y, r in bombs]\n adj = defaultdict(list)\n r_adj = defaultdict(list)\n for bomb1 in b:\n for bomb2 in b:\n if bomb1 == bomb2:\n continue\n if bomb1.enclosed(bomb2):\n adj[bomb1].append(bomb2)\n r_adj[bomb2].append(bomb1)\n\n # // Kosaraju\'s Algorithm for SCC\n stack = []\n visited = set()\n def dfs1(node):\n if node in visited:\n return\n\n visited.add(node)\n for nei in adj[node]:\n dfs1(nei)\n\n stack.append(node)\n \n for bomb in b:\n dfs1(bomb)\n\n who = defaultdict(Bomb)\n visited = set()\n def dfs2(node, root):\n if node in visited:\n return\n visited.add(node)\n who[node] = root\n for nei in r_adj[node]:\n dfs2(nei, root)\n \n while stack:\n curr = stack.pop()\n if curr in visited:\n continue\n dfs2(curr, curr)\n\n \n # // Reversed Topological Sort\n representatives = set(list(who.values()))\n weights = {u: 0 for u in representatives}\n indegree = {u: 0 for u in representatives}\n new_adj = defaultdict(set)\n for u in b:\n for v in adj[u]:\n if who[u] == who[v]:\n continue\n if who[u] in new_adj[who[v]]:\n continue\n new_adj[who[v]].add(who[u])\n indegree[who[u]] += 1\n\n for u in who:\n weights[who[u]] += 1\n \n q = deque()\n for u in indegree:\n if indegree[u] == 0:\n q.append(u)\n\n res = {u: set([u]) for u in representatives}\n visited = set()\n while q:\n for _ in range(len(q)):\n node = q.popleft()\n for child in new_adj[node]:\n if child in visited:\n continue\n \n # // Update set to avoid double counts\n res[child].update(res[node])\n \n indegree[child] -= 1\n if indegree[child] == 0:\n q.append(child)\n visited.add(child)\n \n # // Sum weights inside the set and take max\n maxb = 0\n for u in res:\n curr = 0\n for i in res[u]:\n curr += weights[i]\n maxb = max(maxb, curr)\n\n return maxb\n \n\nclass Bomb:\n def __init__(self, x, y, r):\n self.x = x\n self.y = y\n self.r = r\n\n def enclosed(self, other):\n return self.r ** 2 >= (self.x - other.x) ** 2 + (self.y - other.y) ** 2\n```
2
0
['Breadth-First Search', 'Topological Sort', 'Strongly Connected Component', 'Python3']
2
detonate-the-maximum-bombs
Easy to Understand with video solution
easy-to-understand-with-video-solution-b-zikr
Intuition\n Describe your first thoughts on how to solve this problem. \nWe have a radius/range for each bomb and every bomb in that radius will explode that wi
mrgokuji
NORMAL
2023-06-02T17:42:46.880274+00:00
2023-06-02T18:55:54.912751+00:00
136
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe have a radius/range for each bomb and every bomb in that radius will explode that will start a chain reaction. This implies that we need to constuct a graph where adjecent nodes will be the bomb index in the range.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe\'ll construct a graph whose adj nodes will denote the coordinates of bomb which will explode if Ith bomb exploded.\nNow we\'ll run a DFS on the graph we constructed and calculate the longest chain we have.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2) + O(n^2)--> to construct the graph and run dfs for every node.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n^2) --> as we are constructing graph.\n\n# Video Link : \nhttps://www.youtube.com/watch?v=jqzel5CawPA\n\n# Code\n```\nclass Solution {\npublic:\n void dfs(vector<vector<int>>& graph, int start,vector<bool>& vis,int& len){\n if(vis[start]) return;\n vis[start] = true;\n len++;\n for(int node:graph[start]){\n if(!vis[node]) dfs(graph,node,vis,len);\n }\n\n }\n bool isBombInRange(int x1,int y1,int x2,int y2,int radius){\n float dist = sqrt(pow(x1-x2,2)+pow(y1-y2,2));\n return ceil(dist)<=radius;\n }\n int maximumDetonation(vector<vector<int>>& bombs) {\n vector<vector<int>> graph(bombs.size());\n for(int i=0;i<bombs.size();i++){\n for(int j=i+1;j<bombs.size();j++){\n // if(i!=j){\n int x1 = bombs[i][0];\n int y1 = bombs[i][1];\n int radius1 = bombs[i][2];\n int x2 = bombs[j][0];\n int y2 = bombs[j][1];\n int radius2 = bombs[j][2];\n if(isBombInRange(x1,y1,x2,y2,radius1)){\n graph[i].push_back(j);\n }\n if(isBombInRange(x1,y1,x2,y2,radius2)) graph[j].push_back(i);\n // }\n }\n }\n\n // printGraph(graph);\n\n \n int ans = 0;\n for(int i=0;i<bombs.size();i++){\n // if(!vis[i]){\n vector<bool> vis(bombs.size(),false);\n int temp = 0;\n dfs(graph,i,vis,temp);\n ans = max(ans,temp);\n // }\n }\n return ans;\n }\n\n void printGraph(vector<vector<int>>& graph){\n for(int i=0;i<graph.size();i++){\n for(int node:graph[i]) cout<<node<<" ";\n cout<<endl;\n }\n }\n};\n```
2
0
['Math', 'Depth-First Search', 'Graph', 'Geometry', 'C++']
0
detonate-the-maximum-bombs
Maybe fastest Rust solution (100% beat by runtime and memory)
maybe-fastest-rust-solution-100-beat-by-nwaap
Intuition\nFirst thought was to sort by influence to neighbor bombs, then link top influencers. But I\'ve quickly infered it\'s a wrong way.\n\nSecond thought w
zlumyo
NORMAL
2023-06-02T16:43:24.700486+00:00
2023-06-02T16:47:23.464388+00:00
64
false
# Intuition\nFirst thought was to sort by influence to neighbor bombs, then link top influencers. But I\'ve quickly infered it\'s a wrong way.\n\nSecond thought was describe bombs and ther "victims" as graph. Then there is need to extract separated clusters of connected nodes. Cluster with biggest number of nodes is the answer. And it was bingo! \n\n# Approach\nBuild directed graph where nodes are bombs and edges are connections to bombs affected by blast. Pythagorean theorem is in game here. To avoid floating point arithmetic we can use squared blast radius:\n\n$$r_{i}^2 <= d_{ij}^2 = (x_{i} - x_{j})^2 + (y_{i} - y_{j})^2$$\n\n# Complexity\n- Time complexity:\n$$O(n^3)$$\n\n- Space complexity:\n$$O(n^2)$$\n\n# Code\n```\nimpl Solution {\n // beats 100% by runtime and memory, so code is a bit wired\n pub fn maximum_detonation(bombs: Vec<Vec<i32>>) -> i32 {\n // Deep first graph traversing helper.\n // Pass a starting node to search from. \n fn count_nodes_in_cluster(graph: &Vec<Vec<usize>>, node: usize, stack: &mut Vec<usize>, visited: &mut Vec<bool>) -> usize {\n stack.push(node);\n while let Some(current) = stack.pop() {\n if visited[current] {\n continue;\n }\n visited[current] = true;\n stack.extend(graph[current].iter().cloned());\n }\n\n return visited.iter().filter(|&&flag| flag).count();\n }\n\n let bombs_count = bombs.len(); // to avoid multiple function calling\n let mut visited = vec![false; bombs_count]; // reusable substitute of HashMap\n let mut connected_bombs = vec![Vec::with_capacity(bombs_count-1); bombs_count]; // allocate memory ahead\n\n for i in 0..bombs_count {\n let x_i = bombs[i][0] as i64; // squared value may not fit in i32\n let y_i = bombs[i][1] as i64;\n let r_i = (bombs[i][2] as i64) * (bombs[i][2] as i64);\n\n for j in i + 1..bombs_count {\n let x_j = bombs[j][0] as i64;\n let y_j = bombs[j][1] as i64;\n let r_j = bombs[j][2] as i64;\n\n let d = (x_i - x_j) * (x_i - x_j) + (y_i - y_j) * (y_i - y_j);\n if d <= r_i {\n connected_bombs[i].push(j);\n }\n // don\'t forget to check reverse blast\n if d <= r_j * r_j {\n connected_bombs[j].push(i);\n }\n }\n }\n\n let mut result = 0;\n let mut stack = vec![]; // reusable stack for performance reason\n for i in 0..bombs_count {\n let excluded = count_nodes_in_cluster(&connected_bombs, i, &mut stack, &mut visited);\n if excluded > result {\n result = excluded;\n }\n visited.fill(false);\n }\n\n return result as i32;\n }\n}\n```
2
0
['Graph', 'Geometry', 'Rust']
0
detonate-the-maximum-bombs
🔥🔥Easy To Understand Solution- C++ With Comments🔥🔥
easy-to-understand-solution-c-with-comme-c5de
Intuition\nIn the given 2D vector bombs they are giving a co-ordinate with radius.\nSo intuition is to build an adjacency list in which we can see how \nmany mo
yuvrajkarna27
NORMAL
2023-06-02T15:33:14.009708+00:00
2023-06-02T15:46:53.158407+00:00
531
false
# Intuition\nIn the given 2D vector bombs they are giving a co-ordinate with radius.\nSo intuition is to build an adjacency list in which we can see how \nmany more co-ordinates we can access at a particular index.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSo the Approach is to see from every index at i using radius that how many more indexes we can reach to maximize our answer.By the help of distance formula x1 is i and x2 is j, DistanceBetweenx1ANDx2 = ( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) ) and radius.\nif DistanceBetweenx1ANDx2 <= radius (at i) then we can reach other wise we can\'t.\n\n\n\nAs comments has give follow that to undestand the complete solution.\n\nFEEL FREE TO DISCUSS YOUR IDEAS WE AS A COMMUNITY LETS HELP EACH OTHER.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- In Worst Case:O(n*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n typedef long long ll;\nprivate:\n void dfs(int node,vector<int>*adj,vector<bool>&vis,int &ANS){\n vis[node]=true;\n //Increasing the number of bombs detonated\n ANS+=1;\n //Going through all the adjacent/neighbours nodes\n for(auto &adjNode:adj[node]){\n if(!vis[adjNode]){\n dfs(adjNode,adj,vis,ANS);\n }\n }\n }\npublic:\n int maximumDetonation(vector<vector<int>>& bombs) {\n \n int n=bombs.size();\n vector<int>adj[n];\n\n for(int i=0;i<n;i++){\n // this is the value of first point in graph and radius\n ll x1=(ll)bombs[i][0];\n ll y1=(ll)bombs[i][1];\n ll r1=(ll)bombs[i][2];\n for(int j=0;j<n;j++){\n // this is the value of second point in graph and radius\n ll x2=(ll)bombs[j][0];\n ll y2=(ll)bombs[j][1];\n ll r2=(ll)bombs[j][2];\n //Here we are finding the distance from point (x1,y1) to (x2,y2)\n ll DistanceBetweenx1ANDx2 = ( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) );\n //Checking whether the distance is less than or equal to r1 as up to r1 only our circle \n //can stetch\n if(DistanceBetweenx1ANDx2 <= r1*r1){\n // Here we can state that from index i to index j we can reach by using radius r1\n adj[i].push_back(j);\n }\n }\n }\n\n int ans=0;\n for(int i=0;i<n;i++){\n vector<bool>vis(n,false);\n if(!vis[i]){\n //Here initially we are keeping ANS=0 for every node to see that maximum number of bombs \n //can be detonated from node i\n int ANS=0;\n dfs(i,adj,vis,ANS);\n ans=max(ans,ANS);\n }\n }\n\n return ans;\n }\n};\n```
2
0
['Depth-First Search', 'Graph', 'Recursion', 'C++']
2
detonate-the-maximum-bombs
Java BFS Solution
java-bfs-solution-by-tbekpro-5cvp
Code\n\nclass Solution {\n public int maximumDetonation(int[][] bombs) {\n Arrays.sort(bombs, (o1, o2) -> o2[2] - o1[2]);\n int res = 0;\n
tbekpro
NORMAL
2023-06-02T15:31:21.203843+00:00
2023-06-02T15:31:21.203888+00:00
382
false
# Code\n```\nclass Solution {\n public int maximumDetonation(int[][] bombs) {\n Arrays.sort(bombs, (o1, o2) -> o2[2] - o1[2]);\n int res = 0;\n for (int i = 0; i < bombs.length; i++) {\n int[][] copy = Arrays.copyOf(bombs, bombs.length);\n int count = 1;\n Queue<int[]> queue = new LinkedList<>();\n queue.offer(copy[i]);\n copy[i] = null;\n while (!queue.isEmpty()) {\n int[] arr = queue.poll();\n int y = arr[1], x = arr[0], r = arr[2];\n for (int j = 0; j < copy.length; j++) {\n int[] b = copy[j];\n if (b == null) continue;\n int y1 = b[1], x1 = b[0], r1 = b[2];\n double dist = Math.sqrt(Math.pow(y - y1, 2) + Math.pow(x - x1, 2));\n if (dist <= r) {\n count++;\n queue.offer(b);\n copy[j] = null;\n }\n }\n }\n res = Math.max(count, res);\n }\n return res;\n }\n}\n```
2
0
['Java']
1
detonate-the-maximum-bombs
C++ || DFS || Intuitive || Clean Code
c-dfs-intuitive-clean-code-by-adi1707-834v
Intuition\nThe bombs will detonate all of the bombs which are in its range. So form groups which connects all bombs which are linked to each other.\nCount the n
adi1707
NORMAL
2023-06-02T15:01:04.881847+00:00
2023-06-02T15:01:04.881886+00:00
48
false
# Intuition\nThe bombs will detonate all of the bombs which are in its range. So form groups which connects all bombs which are linked to each other.\nCount the number of bombs connected together in a group. The group with maximum number of bombs will be our answer.\n\n# Approach\nForm the a directed graph which connects the bombs. Run a dfs and count the number of bombs in each graph. The maximum would be our answer.\n\nRefer to the code for better understanding :)\n\n# Complexity\n- Time complexity:O(N*N)\n\n- Space complexity:O(N*N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void dfs(int node, vector<int>& vis, vector<int> graph[], int& c){\n vis[node] = 1;\n c++;\n for(auto child:graph[node]){\n if(vis[child]) continue;\n dfs(child, vis, graph, c);\n }\n }\n\n int maximumDetonation(vector<vector<int>>& bombs) {\n int n = bombs.size();\n vector<int> graph[n];\n for(int i=0; i<n; i++){\n long long r = bombs[i][2];\n int x = bombs[i][0];\n int y = bombs[i][1];\n\n for(int j=0; j<n; j++){\n if(i==j) continue;\n int x1 = bombs[j][0];\n int y1 = bombs[j][1];\n long long r1 = bombs[j][2];\n\n long long dist = (pow(x-x1,2)+pow(y-y1,2));\n if(dist <= (r*r)) graph[i].push_back(j);\n }\n }\n\n int maxi=1;\n for(int i=0; i<n; i++){\n int c=0;\n vector<int> vis(n,0);\n dfs(i, vis, graph, c);\n maxi = max(maxi, c);\n }\n return maxi;\n \n }\n};\n```
2
0
['Depth-First Search', 'Graph', 'Geometry', 'C++']
0
detonate-the-maximum-bombs
✨🔥 Python: DFS Solution 🔥✨
python-dfs-solution-by-patilsantosh-yusp
Approach\n Describe your approach to solving the problem. \nDFS Solution\n\n# Complexity\n- Time complexity: O(N^2)\n Add your time complexity here, e.g. O(n) \
patilsantosh
NORMAL
2023-06-02T13:51:36.252139+00:00
2023-06-02T13:51:36.252178+00:00
103
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nDFS Solution\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 + E + V)\n where\n - N : Length of array\n - E : Number of Edges\n - V : Number of Nodes\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n- Python\n```\nclass Solution:\n def visit(self, node, adj, vis):\n vis[node] = 1\n ans = 1\n for nod in adj[node]:\n if vis[nod] == 0:\n ans += self.visit(nod, adj, vis)\n return ans\n \n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n n = len(bombs)\n adj = {i : [] for i in range(n)}\n\n for i in range(n):\n x1, y1, r1 = bombs[i][0], bombs[i][1], bombs[i][2] \n for j in range(i, n):\n x2, y2, r2 = bombs[j][0], bombs[j][1], bombs[j][2]\n d = ((x1-x2)**2 + (y1-y2)**2)**0.5\n if d <= r1:\n adj[i].append(j)\n if d <= r2:\n adj[j].append(i)\n \n ans = 0\n\n for i in range(n):\n vis = [0] * n\n if vis[i] == 0:\n ans = max(ans, self.visit(i, adj, vis))\n return ans \n```\n# UPVOTE Please!!
2
0
['Python3']
0
detonate-the-maximum-bombs
DFS || Cinch Solution
dfs-cinch-solution-by-bhumit_joshi-ol42
Intuition \n- Determine if a bomb is placed within the destroyable range of other bombs \n- Recall equation of a circle- \n X^2 + Y^2 = R^2\n- Equation for
Bhumit_Joshi
NORMAL
2023-06-02T12:56:40.845594+00:00
2023-06-02T12:56:40.845635+00:00
147
false
# Intuition \n- Determine if a bomb is placed within the destroyable range of other bombs \n- **Recall equation of a circle- \n X^2 + Y^2 = R^2**\n- Equation for bomb Within the Range\n**(X-x)^2 + (Y-y)^2 <= R^2** \n- If there is a bomb within range, establish a connection.\n- Detonate each bomb and identify the one capable of detonating the maximum number of bombs.\n\n# Code\n```\nclass Solution {\npublic:\n\n int dfs(int node, vector<int> adj[], vector<bool>& vis){\n vis[node] = 1;\n int count=1;\n for(auto it : adj[node])\n if(!vis[it])\n count += dfs(it, adj, vis);\n return count;\n }\n\n int maximumDetonation(vector<vector<int>>& nums) {\n int n = nums.size();\n vector<int> adj[n];\n\n for(int i=0; i<n; i++){\n for(int j=0; j<n; j++){\n if(i == j)\n continue;\n int x = abs(nums[i][0] - nums[j][0]);\n int y = abs(nums[i][1] - nums[j][1]);\n if( pow(x,2) + pow(y,2) <= pow(nums[i][2],2) )\n adj[i].push_back(j);\n }\n }\n int ans=0;\n for(int i=0; i<n; i++){\n vector<bool> vis(n, 0);\n ans = max(ans, dfs(i, adj, vis));\n }\n return ans;\n }\n};\n\n```
2
0
['Depth-First Search', 'C++']
1
detonate-the-maximum-bombs
✅ [Solution][Swift] DFS
solutionswift-dfs-by-adanilyak-0fwx
TC: O(n * n)\nSC: O(n * n)\n\nclass Solution {\n func maximumDetonation(_ bombs: [[Int]]) -> Int {\n func check(\n point: (x: Int, y: Int),
adanilyak
NORMAL
2023-06-02T12:16:44.287850+00:00
2023-06-02T12:16:44.287893+00:00
94
false
**TC:** O(n * n)\n**SC:** O(n * n)\n```\nclass Solution {\n func maximumDetonation(_ bombs: [[Int]]) -> Int {\n func check(\n point: (x: Int, y: Int),\n isInside circle: (x: Int, y: Int, r: Int)\n ) -> Bool {\n let distance = sqrt(\n pow(Double(point.x - circle.x), 2.0) + pow(Double(point.y - circle.y), 2.0)\n )\n return Double(circle.r) >= distance\n }\n\n let n = bombs.count\n var map = [Int: [Int]]()\n var result = 1\n\n for i in 0..<n {\n map[i] = []\n for j in 0..<n where j != i {\n guard check(point: (bombs[j][0], bombs[j][1]), isInside: (bombs[i][0], bombs[i][1], bombs[i][2])) \n else { continue }\n map[i]?.append(j)\n }\n }\n\n for i in 0..<n {\n var used = Set<Int>()\n var current = Set<Int>([i])\n while !current.isEmpty {\n let node = current.removeFirst()\n used.insert(node)\n for adj in map[node]! where !used.contains(adj) {\n current.insert(adj)\n }\n }\n\n result = max(result, used.count)\n }\n\n return result\n }\n}\n```
2
0
['Depth-First Search', 'Swift']
0
detonate-the-maximum-bombs
Java || 3 ms 100% || Build graph, then DFS from each bomb
java-3-ms-100-build-graph-then-dfs-from-nmg1k
This code converts the bomb location and radius to a graph where each bomb is a node in the graph, and the directional edges of the graph are the other bombs th
dudeandcat
NORMAL
2023-06-02T09:56:26.261787+00:00
2023-06-02T21:53:20.756174+00:00
446
false
This code converts the bomb location and radius to a graph where each bomb is a node in the graph, and the directional edges of the graph are the other bombs that the current bomb can reach with its blast radius. After the graph is build into the variable `links[][]`, a depth-first-search (DFS) is performed starting from each bomb, to determine the total number of bombs to explode from each starting bomb.\n\nThis code is speed optimized. Most other fast code examples for this leetcode problem, use a List\\<Integer> to contain the edges of the graph. This code gains some speed by using a byte array terminated with a -1, to contain the edges of the graph. The primitive data type `byte` array can be faster in execution than the more complex `List` data type. We can use the byte array because we know the maximum number of edges for any graph node, will be 100, according to the constraints section of the leetcode problem description. And 100 is a reasonable length to allocate in memory.\n\nIf there are `n` bombs in the passed `bombs[]` array, the graph will consist of a 2-D byte array `byte[][] links = new byte[n][n+1]` where the first index is the node number (index in the `bombs[]` array). The second index is the index into the edges node numbers, terminatred by a -1 value.\n\nThis code has runtime as fast as 3ms in June 2023, but usually (~70% of submits) has runtime of 4ms. \nIf useful, please upvote.\n```\nclass Solution {\n public int maximumDetonation(int[][] bombs) {\n int n = bombs.length;\n if (n <= 1) return n;\n if (n == 2) return twoBombs(bombs);\n \n byte[][] links = new byte[n][n + 1];\n int[] linksLen = new int[n];\n for (int b = 0; b < n; b++)\n buildLinks(links, linksLen, bombs, bombs[b], b);\n \n int maxLinks = 0;\n for (int i = n - 1; i >= 0; i--) {\n if (linksLen[i] > maxLinks) maxLinks = linksLen[i];\n links[i][linksLen[i]] = (byte)-1;\n }\n if (maxLinks == 0 || maxLinks == n - 1) return maxLinks + 1;\n \n int maxExplosions = 0;\n for (int i = n - 1; i >= 0; i--) {\n maxExplosions = Math.max(maxExplosions, countExplosions(links, new boolean[n], i));\n if (maxExplosions == n) break;\n }\n return maxExplosions;\n }\n \n \n private int countExplosions(byte[][] links, boolean[] used, int b) {\n used[b] = true;\n int explosions = 1;\n for (int b1 : links[b]) {\n if (b1 < 0) break;\n if (!used[b1]) explosions += countExplosions(links, used, b1);\n }\n return explosions;\n }\n \n \n private void buildLinks(byte[][] links, int[] linksLen, int[][] bombs, int[] bomb, int b) {\n int x = bomb[0];\n int y = bomb[1];\n long radius = (long)bomb[2] * bomb[2];\n for (int b1 = links.length - 1; b1 > b; b1--) {\n int[] bomb1 = bombs[b1];\n long dist = distance(x, y, bomb1[0], bomb1[1]);\n if (dist <= radius) links[b][linksLen[b]++] = (byte)b1;\n if (dist <= (long)bomb1[2] * bomb1[2]) links[b1][linksLen[b1]++] = (byte)b;\n }\n }\n \n \n private long distance(int x1, int y1, int x2, int y2) {\n return (long)(x1 - x2) * (x1 - x2) + (long)(y1 - y2) * (y1 - y2);\n }\n \n \n private int twoBombs(int[][] bombs) {\n int[] b0 = bombs[0];\n int[] b1 = bombs[1];\n long dist = distance(b0[0], b0[1], b1[0], b1[1]);\n if (dist <= (long)b0[2] * b0[2] || dist <= (long)b1[2] * b1[2]) return 2;\n return 1;\n }\n}\n```
2
0
['Java']
0
detonate-the-maximum-bombs
C++ || DFS || EASY TO UNDERSTAND
c-dfs-easy-to-understand-by-coder_shaile-6tz0
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
coder_shailesh411
NORMAL
2023-06-02T09:34:34.016290+00:00
2023-06-02T09:34:34.016319+00:00
1,390
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 void dfs(vector<int>&vis,vector<vector<int>>&temp,int &t,int& i){\n vis[i]=1;\n t++;\n for(int j=0;j<temp[i].size();j++){\n if(!vis[temp[i][j]]){\n \n dfs(vis,temp,t,temp[i][j]);\n }\n }\n }\n\n int maximumDetonation(vector<vector<int>>& bombs) {\n int n=bombs.size();\n vector<vector<int>>temp(n);\n\n for(int i=0;i<n;i++){\n long long x=bombs[i][0];\n long long y=bombs[i][1];\n long long r=bombs[i][2];\n for(int j=0;j<n;j++){\n if(i!=j){\n long long x1=abs(x-bombs[j][0]);\n long long y1=abs(y-bombs[j][1]);\n if(x1*x1+y1*y1<=r*r){\n temp[i].push_back(j);\n }\n }\n }\n }\n\n \n int ans=INT_MIN;\n for(int i=0;i<n;i++){\n int t=0;\n vector<int>vis(n,0);\n dfs(vis,temp,t,i);\n ans=max(ans,t);\n \n }\n return ans;\n }\n};\n```
2
0
['Depth-First Search', 'Graph', 'C++']
1
detonate-the-maximum-bombs
Python Approach by using Euclidean distance and DFS
python-approach-by-using-euclidean-dista-mntf
\n# Code\n\nclass Solution:\n # DFS ...!\n def dfs(self, i):\n self.visit[i] = 1\n \n for node in self.d[i]:\n if self.vis
Bala_1543
NORMAL
2023-06-02T09:14:12.342159+00:00
2023-06-02T09:14:12.342203+00:00
152
false
\n# Code\n```\nclass Solution:\n # DFS ...!\n def dfs(self, i):\n self.visit[i] = 1\n \n for node in self.d[i]:\n if self.visit[node] == 1:\n continue\n self.dfs(node)\n\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n n = len(bombs)\n d = {}\n for i in range(n): d[i] = set()\n\n for i in range(n):\n for j in range(n):\n if i == j: continue\n\n # Euclidean Distance\n temp =(bombs[i][0]-bombs[j][0])**2+(bombs[i][1]-bombs[j][1])**2 \n\n if temp <= bombs[j][2]**2: d[j].add(i)\n if temp <= bombs[i][2]**2: d[i].add(j)\n \n self.d = d\n ans = 1\n for i in range(n):\n self.visit = [0]*n\n self.dfs(i)\n ans = max(ans , sum(self.visit)) # No.of 1\'s\n\n return ans\n```
2
0
['Python3']
0
detonate-the-maximum-bombs
Python short and clean. DFS. Functional programming.
python-short-and-clean-dfs-functional-pr-zeez
Approach\nTL;DR, Similar to Editorial Solution but shorter and cleaner.\n\n# Complexity\n- Time complexity: O(n ^ 3)\n\n- Space complexity: O(n ^ 2)\n\n# Code\n
darshan-as
NORMAL
2023-06-02T04:35:12.450237+00:00
2023-06-02T04:35:12.450283+00:00
605
false
# Approach\nTL;DR, Similar to [Editorial Solution](https://leetcode.com/problems/detonate-the-maximum-bombs/editorial/) but shorter and cleaner.\n\n# Complexity\n- Time complexity: $$O(n ^ 3)$$\n\n- Space complexity: $$O(n ^ 2)$$\n\n# Code\n```python\nclass Solution:\n def maximumDetonation(self, bombs: list[list[int]]) -> int:\n Bomb = tuple[int, int, int]\n T = Hashable\n Graph = Mapping[T, Collection[T]]\n\n def in_range(b1: Bomb, b2: Bomb) -> bool:\n return (b1[0] - b2[0]) ** 2 + (b1[1] - b2[1]) ** 2 <= b1[2] ** 2\n\n def connections(graph: Graph, src: T, seen: set[T]) -> int:\n return seen.add(src) or 1 + sum(connections(graph, x, seen) for x in graph[src] if x not in seen)\n\n g = {i: tuple(j for j, b2 in enumerate(bombs) if in_range(b1, b2)) for i, b1 in enumerate(bombs)}\n return max(connections(g, x, set()) for x in g)\n\n\n```
2
0
['Depth-First Search', 'Graph', 'Geometry', 'Python', 'Python3']
1
detonate-the-maximum-bombs
JAVA || DFS || C++
java-dfs-c-by-deepakpatel4115-t220
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
deepakpatel4115
NORMAL
2023-06-02T03:33:36.959567+00:00
2023-06-02T03:33:36.959613+00:00
252
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 int maximumDetonation(int[][] bombs) {\n int ans = 0;\n int n = bombs.length;\n boolean[] visited = new boolean[n];\n int var;\n for(int i=0; i<n; i++) {\n Arrays.fill(visited, false);\n var = dfs(i, bombs, visited);\n ans = Math.max(ans, var);\n }\n return ans;\n }\n\n int dfs(int ind, int[][] bombs, boolean[] visited) {\n visited[ind]=true;\n long r = bombs[ind][2];\n r = r*r;\n int ans = 0;\n for(int i=0; i<bombs.length; i++) {\n if(i==ind || visited[i])\n continue;\n long xDiff = (bombs[ind][0]-bombs[i][0]);\n long yDiff = (bombs[ind][1]-bombs[i][1]);\n long dis = xDiff*xDiff + yDiff*yDiff;\n if(dis<=r) {\n ans+=dfs(i, bombs, visited);\n }\n }\n return ans+1;\n }\n}\n```
2
0
['Depth-First Search', 'C++', 'Java']
0
detonate-the-maximum-bombs
Swift | Minimal BFS
swift-minimal-bfs-by-upvotethispls-567u
BFS (accepted answer)\n\nclass Solution {\n func maximumDetonation(_ bombs: [[Int]]) -> Int {\n\t\n func contains(_ a:[Int], _ b:[Int]) -> Bool {\n
UpvoteThisPls
NORMAL
2023-06-02T02:43:35.659159+00:00
2023-06-02T05:29:24.637862+00:00
728
false
**BFS (accepted answer)**\n```\nclass Solution {\n func maximumDetonation(_ bombs: [[Int]]) -> Int {\n\t\n func contains(_ a:[Int], _ b:[Int]) -> Bool {\n let (deltaX, deltaY) = (a[0]-b[0], a[1]-b[1])\n return deltaX * deltaX + deltaY * deltaY <= a[2] * a[2]\n }\n \n let bombsInRadius = bombs.indices.map { i in\n bombs.indices.filter { j in contains(bombs[i], bombs[j]) }\n }\n \n func bfs(_ start: Int) -> Int {\n var bfs = Set([start]), visited = bfs\n while !bfs.isEmpty {\n bfs = Set(bfs.flatMap { bomb in bombsInRadius[bomb]}).subtracting(visited)\n visited.formUnion(bfs)\n }\n return visited.count\n }\n \n return bombs.indices.map(bfs).max()!\n }\n}\n```
2
0
['Swift']
0
detonate-the-maximum-bombs
C++ || using graph
c-using-graph-by-_biranjay_kumar-xm05
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
_Biranjay_kumar_
NORMAL
2023-06-02T01:41:00.680701+00:00
2023-06-02T01:41:00.680750+00:00
2,207
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#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```
2
0
['C++']
0
detonate-the-maximum-bombs
Ruby solution with BFS (100%/100%)
ruby-solution-with-bfs-100100-by-dtkalla-knw8
Intuition\nFor each bomb, find the bombs it immediately causes to explode, then BFS to find how many it explodes in total.\n\n# Approach\n1. Create a hash of bo
dtkalla
NORMAL
2023-06-02T00:14:30.835239+00:00
2023-06-02T00:19:13.511789+00:00
77
false
# Intuition\nFor each bomb, find the bombs it immediately causes to explode, then BFS to find how many it explodes in total.\n\n# Approach\n1. Create a hash of bombs that each bomb will directly explode (each key is an index, each value is an array of indices of other bombs).\n2. Iterate through every pair of bombs. For each pair:\n - Use the distance formula to check if the first bomb explodes the other. If so, add it to the hash.\n - Check if the second bomb explodes the first bomb, and add it to the *second* bomb\'s array if so.\n3. Initialize the maximum to be zero (in case there are no bombs).\n4. BFS from each bomb to see all other bombs it explodes:\n - Create a set of bombs that have exploded.\n - Create a queue with the first bomb.\n - For each bomb in the queue, check if it explodes any bombs that haven\'t exploded yet. If so, add those bombs to the checked set and the queue.\n - Once queue is empty, compare the size of the checked (exploded) bombs to max, and take whichever is bigger.\n5. Return max.\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(n^2)$$\n\n# Code\n```\ndef maximum_detonation(bombs)\n chain = Hash.new { |h,k| h[k] = [] }\n\n bombs.each_with_index do |bomb,i|\n bombs.each_with_index do |bomb2,j|\n if i > j\n a,b,c = bomb\n d,e,f = bomb2\n\n chain[i] << j if (a-d)**2 + (b-e)**2 <= c**2\n chain[j] << i if (a-d)**2 + (b-e)**2 <= f**2\n end\n end\n end\n\n max = 0\n\n (0...bombs.length).each do |i|\n checked = Set[i]\n queue = checked.to_a\n\n until queue.empty?\n bomb = queue.shift\n connections = chain[bomb]\n connections.each do |connection|\n queue << connection unless checked.include?(connection)\n checked.add(connection)\n end\n end\n\n max = checked.size if checked.size > max\n end\n\n max\nend\n```
2
0
['Ruby']
1
detonate-the-maximum-bombs
🗓️ Daily LeetCoding Challenge June, Day 2
daily-leetcoding-challenge-june-day-2-by-e1d0
This problem is the Daily LeetCoding Challenge for June, Day 2. Feel free to share anything related to this problem here! You can ask questions, discuss what yo
leetcode
OFFICIAL
2023-06-02T00:00:18.667680+00:00
2023-06-02T00:00:18.667731+00:00
4,455
false
This problem is the Daily LeetCoding Challenge for June, 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/detonate-the-maximum-bombs/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 these 3 approaches in the official solution</summary> **Approach 1:** Depth-First Search, Recursive **Approach 2:** Depth-First Search, Iterative **Approach 3:** Breadth-First Search </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>
2
0
[]
16
detonate-the-maximum-bombs
[C#] BFS Graph Traversal
c-bfs-graph-traversal-by-sh0wmet3hc0de-dz5l
Intuition\nPorted from Java from: https://leetcode.com/problems/detonate-the-maximum-bombs/solutions/1623563/simple-java-bfs/?page=3\n# Approach\nDue to its rad
sh0wMet3hC0de
NORMAL
2022-12-28T07:53:02.381653+00:00
2022-12-28T07:53:02.381700+00:00
554
false
# Intuition\nPorted from Java from: https://leetcode.com/problems/detonate-the-maximum-bombs/solutions/1623563/simple-java-bfs/?page=3\n# Approach\nDue to its radial exploration nature, BFS almost litteraly fits this problem. I confess I did try first Union-Find, but could only get 125 of LeetCode\'s test cases to pass...\n\nThe first part of the BFS solution consists in computing the indiviual reach of each bomb (using Euclidean distance) and storing it in a dictionary. Note that bombs that don\'t reach any other bombs are not added to the dictonary:\n\n```\nDictionary<int,List<int>> map = new ();\n\nfor(int i=0; i < bombs.Length;i++){\n for(int j=0; j< bombs.Length;j++){\n if(j==i) \n continue;\n long sum = (long)(bombs[i][0]-bombs[j][0])*(long)(bombs[i][0]-bombs[j][0])+(long)(bombs[i][1]-bombs[j][1])*(long)(bombs[i][1]-bombs[j][1]);\n long self = (long)bombs[i][2]*(long)bombs[i][2];\n if(self >= sum){\n if(!map.ContainsKey(i)){\n map.Add(i,new List<int>());\n }\n map[i].Add(j);\n }\n }\n}\n```\nThe second par is BFS itself. Note that the visited array is reset for every new starting node/traversal.\n```\nfor(int i=0;i< bombs.Length;i++){\n...\n int[] visit = new int[bombs.Length];\n```\nAt the end of each traversal, the maximum bomb reach is updated:\n```\nmax = Math.Max(max,count);\n\n```\nBFS will allow us to accumulate and explore the reach of each bomb. Each traversal will be optmized since we\'ll avoid repeated operations by marking the visited nodes. \nThe fact that we already have a precomputed dictionary with the individual reach of each bomb also makes a huge performance difference when running the BFS traversal for each bomb.\n\n# Code\n```\npublic class Solution {\n\n public int MaximumDetonation(int[][] bombs) {\n Dictionary<int,List<int>> map = new ();\n \n for(int i=0; i < bombs.Length;i++){\n for(int j=0; j< bombs.Length;j++){\n if(j==i) \n continue;\n long sum = (long)(bombs[i][0]-bombs[j][0])*(long)(bombs[i][0]-bombs[j][0])+(long)(bombs[i][1]-bombs[j][1])*(long)(bombs[i][1]-bombs[j][1]);\n long self = (long)bombs[i][2]*(long)bombs[i][2];\n if(self >= sum){\n if(!map.ContainsKey(i)){\n map.Add(i,new List<int>());\n }\n map[i].Add(j);\n }\n }\n }\n int max = 1;\n \n for(int i=0;i< bombs.Length;i++){\n if(!map.ContainsKey(i)){\n continue;\n }\n int[] visit = new int[bombs.Length];\n int count = 1;\n Queue<int> q = new ();\n q.Enqueue(i);\n visit[i] = 1;\n while(q.Count > 0){\n int size = q.Count;\n while(size > 0){\n int cur = q.Dequeue();\n if(!map.ContainsKey(cur)){\n size--;\n continue;\n }\n foreach(int x in map[cur]){\n if(visit[x]==1) \n continue;\n q.Enqueue(x);\n visit[x] = 1;\n count++;\n }\n size--;\n }\n }\n max = Math.Max(max,count);\n }\n return max;\n }\n}\n```
2
0
['Breadth-First Search', 'C#']
0
detonate-the-maximum-bombs
C
c-by-tinachien-zy17
\nint maximumDetonation(int** bombs, int bombsSize, int* bombsColSize){\n bool* check = calloc(bombsSize, sizeof(bool));\n bool** attach = malloc(bombsSiz
TinaChien
NORMAL
2022-11-05T08:01:23.569812+00:00
2022-11-05T08:01:23.569844+00:00
71
false
```\nint maximumDetonation(int** bombs, int bombsSize, int* bombsColSize){\n bool* check = calloc(bombsSize, sizeof(bool));\n bool** attach = malloc(bombsSize * sizeof(bool*));\n for(int i = 0; i < bombsSize; i++){\n attach[i] = calloc(bombsSize , sizeof(bool));\n }\n\n for(int i = 0; i < bombsSize; i++){\n attach[i][i] = true;\n for(int j = i+1; j < bombsSize; j++){\n int x = abs(bombs[i][0] - bombs[j][0] ) ;\n int y = abs(bombs[i][1] - bombs[j][1] ) ;\n long long dis = (long long)x*x + (long long)y*y;\n if(dis <= (long long)bombs[i][2]*bombs[i][2])\n attach[i][j] = true;\n if(dis <= (long long)bombs[j][2]*bombs[j][2])\n attach[j][i] = true;\n }\n }\n \n int* stack1 = malloc(bombsSize * sizeof(int));\n int* stack2 = malloc(bombsSize * sizeof(int));\n int id1 = 0, id2 = 0;\n int max = 1;\n for(int i = 0; i < bombsSize; i++){\n check = calloc(bombsSize, sizeof(bool));\n int cur = 1;\n check[i] = true;\n stack1[id1] = i;\n id1++;\n while(id1 || id2){\n if(id1){\n for(int j = 0; j < id1; j++){\n int p = stack1[j];\n for(int k = 0; k < bombsSize; k++){\n if(attach[p][k] && check[k] == false){\n cur++;\n check[k] = true;\n stack2[id2] = k;\n id2++;\n }\n }\n }\n id1 = 0;\n }\n else{\n for(int j = 0; j < id2; j++){\n int p = stack2[j];\n for(int k = 0; k < bombsSize; k++){\n if(attach[p][k] && check[k] == false){\n cur++;\n check[k] = true;\n stack1[id1] = k;\n id1++;\n }\n }\n }\n id2 = 0;\n }\n }\n max = fmax(max, cur);\n }\n return max;\n}\n```
2
0
['Breadth-First Search']
0
detonate-the-maximum-bombs
C++ || Using DFS || Neat code with comments
c-using-dfs-neat-code-with-comments-by-a-bc94
\nclass Solution {\npublic:\n void dfs(int node, vector<bool>&visited, vector<int>adj[], int &currDiffused){\n \n currDiffused += 1;// increasi
AvnUtk_26
NORMAL
2022-10-11T21:32:46.799614+00:00
2022-10-11T21:32:46.799638+00:00
656
false
```\nclass Solution {\npublic:\n void dfs(int node, vector<bool>&visited, vector<int>adj[], int &currDiffused){\n \n currDiffused += 1;// increasing the number of bombs getting detonated as we do dfs traversal\n \n for(auto child : adj[node]){\n if(!visited[child]){\n visited[child] = true;\n dfs(child, visited, adj, currDiffused);\n }\n }\n }\n int maximumDetonation(vector<vector<int>>& arr) {\n \n int n = arr.size();\n vector<int>adj[n];\n \n //forming adjacency list\n for(int i = 0; i < n; i++){\n \n long long x = arr[i][0], y = arr[i][1], r = arr[i][2];\n for(int j = 0; j < n; j++){\n \n if(i == j) continue;// current cirle(node) can\'t have itself as its adjacent node\n \n long long xx = arr[j][0], yy = arr[j][1];\n long long diffx = (x - xx) * (x - xx), diffy = (y - yy) * (y - yy), rSquare = r * r;\n if(diffx + diffy <= rSquare){// jth bomb will also diffuse if it\'s center lies inside the ith bomb\'s range, so jth bomb will be adjacent node to ith bomb\n adj[i].push_back(j);\n }\n \n }\n }\n \n int maxDiffused = 0;//will store maximum bombs that can be detonated\n for(int node = 0; node < n; node++){\n \n vector<bool>visited(n, false);\n \n int currDiffused = 0;// It stores maximum bombs that will be detonated, if we detonate current bomb node\n if(!visited[node]){\n \n visited[node] = true;\n dfs(node, visited, adj, currDiffused);\n }\n \n maxDiffused = max(maxDiffused, currDiffused);\n }\n \n return maxDiffused;\n }\n};\n```
2
0
['Depth-First Search', 'Graph', 'Geometry', 'C++']
0
detonate-the-maximum-bombs
Easy to understand Java solution using BFS
easy-to-understand-java-solution-using-b-3f4s
See the solution here:\nhttps://github.com/Freeze777/SDE-Interviewer-Notes/blob/main/LeetCodeJava/src/main/java/leetcode/medium/graph/DetonateMaxBombs.java
freeze_francis
NORMAL
2022-10-08T17:30:39.116167+00:00
2022-10-08T17:30:39.116211+00:00
663
false
See the solution here:\nhttps://github.com/Freeze777/SDE-Interviewer-Notes/blob/main/LeetCodeJava/src/main/java/leetcode/medium/graph/DetonateMaxBombs.java
2
0
['Breadth-First Search']
0
detonate-the-maximum-bombs
Easy-understanding || Python || Faster than 85%
easy-understanding-python-faster-than-85-sb7f
Don\'t be afraid about the size of my code, I just break this down in classes and methods! What I did was converte the bombs in a graph, when the ditance betwee
duduita
NORMAL
2022-09-22T22:51:12.822282+00:00
2022-09-22T22:51:49.321540+00:00
1,022
false
Don\'t be afraid about the size of my code, I just break this down in classes and methods! What I did was converte the bombs in a graph, when the ditance between one bomb and another is smaller than the radius of the source bomb, we connect those two bombs on the graph. \n\nAfter this, we can do a DFS approach and use the visited set as the size of the bomb chain. \n\nThe biggest time complexity is the DFS algorithms that is O(V + E), where V is the number of vertices (bombs) and E is the number of edges (connected bombs).\n\n\tfrom collections import defaultdict\n\n\tclass Solution:\n\t\tdef maximumDetonation(self, bombs: List[List[int]]) -> int:\n \n\t\t\tself.graph = self.bombs_to_graph(bombs)\n\t\t\tprint(self.graph.graph)\n\t\t\tans = 1\n\t\t\tself.dp = [0]*len(bombs)\n\t\t\tfor i in range(len(bombs)):\n\t\t\t\tvisited = set()\n\t\t\t\tself.DFS(i, visited)\n\t\t\t\tans = max(ans, len(visited))\n\t\t\treturn ans\n\n\n\n\n\t\tdef DFS(self, v, visited):\n\n\t\t\tvisited.add(v)\n\t\t\tfor neigh in self.graph.graph[v]:\n\t\t\t\tif neigh not in visited:\n\t\t\t\t\tself.DFS(neigh, visited)\n\n\t\tdef bombs_to_graph(self, bombs):\n\t\t\tgraph = Graph()\n\t\t\tfor i_s, source in enumerate(bombs):\n\t\t\t\tfor i_d, dest in enumerate(bombs):\n\t\t\t\t\tif i_s == i_d: continue\n\n\t\t\t\t\tif self.is_on_range(source, dest):\n\t\t\t\t\t\tgraph.add_edge(i_s, i_d)\n\n\t\t\treturn graph\n\n\t\tdef is_on_range(self, source, dest):\n\n\t\t\tdist = ((source[0] - dest[0])**2 + (source[1] - dest[1])**2)**0.5\n\t\t\treturn dist <= source[2]\n \n \n\tclass Graph:\n\t\tdef __init__(self):\n\t\t\tself.graph = defaultdict(list)\n\n\t\tdef add_edge(self, s, d):\n\t\t\tself.graph[s].append(d)
2
0
['Depth-First Search', 'Graph', 'Python', 'Python3']
1
detonate-the-maximum-bombs
Java DFS
java-dfs-by-java_programmer_ketan-werr
\nclass Solution {\n public int maximumDetonation(int[][] bombs) {\n int n = bombs.length;\n Circle[] circles = new Circle[n];\n for(int
Java_Programmer_Ketan
NORMAL
2022-09-21T15:13:53.963310+00:00
2022-09-21T15:13:53.963347+00:00
844
false
```\nclass Solution {\n public int maximumDetonation(int[][] bombs) {\n int n = bombs.length;\n Circle[] circles = new Circle[n];\n for(int i=0;i<n;i++) circles[i] = new Circle(bombs[i][0],bombs[i][1],bombs[i][2]);\n List<List<Integer>> graph = new ArrayList<>();\n for(int i=0;i<n;i++) graph.add(new ArrayList<>());\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n if(i==j) continue;\n if(circles[i].canDetonate(circles[j]))\n graph.get(i).add(j);\n }\n }\n int answer = 0;\n for(int i=0;i<n;i++) answer = Math.max(answer,dfs(graph,new boolean[n],i));\n return answer;\n }\n private int dfs(List<List<Integer>> graph, boolean[] visited, int node){\n int res = 1;\n visited[node] = true;\n for(int child: graph.get(node)){\n if(visited[child]) continue;\n res += dfs(graph,visited,child);\n }\n return res;\n }\n}\nclass Circle{\n int x;\n int y;\n int r;\n\n public Circle(int x, int y, int r) {\n this.x = x;\n this.y = y;\n this.r = r;\n }\n public boolean canDetonate(Circle other){\n return this.r>=Math.sqrt(Math.pow(Math.abs(this.x-other.x),2)+Math.pow(Math.abs(this.y-other.y),2));\n }\n \n}\n```
2
0
['Depth-First Search', 'Java']
1
detonate-the-maximum-bombs
[Java] Easy and intuitive with explaination || Graph || DFS || Geometry
java-easy-and-intuitive-with-explainatio-rj7x
\nclass Solution {\n /*\n Make directed graph\n u -> v means, v is in the range of u\n check from which node maximum nodes can be reached and return
khushalabrol
NORMAL
2022-07-21T10:16:07.929147+00:00
2022-07-21T10:16:07.929199+00:00
730
false
```\nclass Solution {\n /*\n Make directed graph\n u -> v means, v is in the range of u\n check from which node maximum nodes can be reached and return the number of nodes reached\n */\n public int maximumDetonation(int[][] bombs) {\n Map<Integer, List<Integer>> graph = new HashMap<>();\n \n int n = bombs.length;\n for(int i = 0; i< n; i++){\n graph.put(i, new ArrayList<>());\n for(int j = 0; j< n; j++){\n if(i == j) continue;\n if(inRange(bombs[i], bombs[j]))\n graph.get(i).add(j);\n }\n }\n \n int max = 0;\n for(int i = 0; i< n; i++){\n max = Math.max(max, dfs(i, graph, new HashSet<>()));\n }\n return max;\n }\n \n private boolean inRange(int[] u, int[] v){\n // (x-a)^2 + (y-b)^2 = R^2 -> point (a, b) is at border\n // (x-a)^2 + (y-b)^2 < R^2 -> point (a, b) is inside the circle\n // (x-a)^2 + (y-b)^2 > R^2 -> point (a, b) is outside the circle\n return Math.pow(u[0]-v[0], 2) + Math.pow(u[1]-v[1], 2) <= Math.pow(u[2], 2);\n }\n \n private int dfs(int node, Map<Integer, List<Integer>> graph, Set<Integer> visited){\n if(visited.contains(node)) return 0;\n visited.add(node);\n int res = 0;\n for(int neigh: graph.get(node)){\n res += dfs(neigh, graph, visited);\n }\n return res + 1;\n }\n}\n```
2
0
['Depth-First Search', 'Graph', 'Java']
0
detonate-the-maximum-bombs
Java with comments 11ms beats 100% DFS
java-with-comments-11ms-beats-100-dfs-by-y9bn
graph is a adjacency list.\n\nclass Solution {\n public int maximumDetonation(int[][] bombs) {\n int n = bombs.length;\n List<Integer>[] graph
ar9
NORMAL
2022-04-16T17:59:23.766573+00:00
2022-04-28T12:44:45.984575+00:00
420
false
graph is a adjacency list.\n```\nclass Solution {\n public int maximumDetonation(int[][] bombs) {\n int n = bombs.length;\n List<Integer>[] graph = new List[n];\n for (int i = 0; i < n; i++) graph[i] = new ArrayList<Integer>();\n\t\t// O(n^2 /2) by using j = i+1\n\t\t for (int i = 0; i < n; i++) {\n for (int j = i+1; j < n; j++) {\n // use double since multiplying large values like 10^5 will cause overflow\n double dx = bombs[i][0] - bombs[j][0];\n double dy = bombs[i][1] - bombs[j][1];\n double r1 = bombs[i][2], r2 = bombs[j][2];\n double dist = dx * dx + dy * dy;\n if ( dist <= r1 * r1) graph[i].add(j);\n if ( dist <= r2 * r2) graph[j].add(i);\n }\n \n }\n boolean[] visited = new boolean[n];\n int ans = 0;\n for (int i = 0; i < n; i++) {\n ans = Math.max(ans, dfs(graph, i, visited));\n if (ans == n) return ans; //all of the nodes can be visited\n Arrays.fill(visited, false);\n }\n return ans;\n }\n private int dfs(List<Integer>[] graph, int i, boolean[] visited) {\n int cc = 0;\n if (visited[i]) return 0;\n visited[i] = true;\n for (int neigh: graph[i]) {\n cc += dfs(graph, neigh, visited);\n }\n return cc + 1;\n }\n \n}\n```
2
0
['Depth-First Search', 'Java']
0
detonate-the-maximum-bombs
Python Solution that you want :
python-solution-that-you-want-by-goxy_co-jvj1
\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n if len(bombs)==1:\n return 1\n \n adlist={i
goxy_coder
NORMAL
2022-03-21T13:20:28.075911+00:00
2022-03-21T13:20:28.075956+00:00
846
false
```\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n if len(bombs)==1:\n return 1\n \n adlist={i:[] for i in range(len(bombs))}\n \n for i in range(len(bombs)):\n x1,y1,r1=bombs[i]\n for j in range(i+1,len(bombs)):\n x2,y2,r2=bombs[j]\n dist=((x2-x1)**2+(y2-y1)**2)**(1/2)\n if dist<=r1:\n adlist[i].append(j) \n if dist<=r2:\n adlist[j].append(i)\n \n def dfs(adlist,seen,start):\n seen.add(start)\n for i in adlist[start]:\n if i not in seen:\n dfs(adlist,seen,i)\n maxx=1 \n for v in adlist:\n seen=set()\n seen.add(v)\n dfs(adlist,seen,v)\n maxx=max(maxx,len(seen))\n return maxx\n```
2
0
['Depth-First Search', 'Python', 'Python3']
0
detonate-the-maximum-bombs
c# : Easy Solution
c-easy-solution-by-rahul89798-1vj2
\tpublic class Solution\n\t{\n\t\tpublic int MaximumDetonation(int[][] bombs)\n\t\t{\n\t\t\tint max = 0;\n\t\t\tDictionary> graph = new Dictionary>();\n\n\t\t\t
rahul89798
NORMAL
2022-02-26T13:54:55.500765+00:00
2022-02-26T13:55:11.166363+00:00
102
false
\tpublic class Solution\n\t{\n\t\tpublic int MaximumDetonation(int[][] bombs)\n\t\t{\n\t\t\tint max = 0;\n\t\t\tDictionary<int, List<int>> graph = new Dictionary<int, List<int>>();\n\n\t\t\tfor (int i = 0; i < bombs.GetLength(0); i++)\n\t\t\t{\n\t\t\t\tif (!graph.ContainsKey(i))\n\t\t\t\t\tgraph[i] = new List<int>();\n\n\t\t\t\tfor (int j = i + 1; j < bombs.GetLength(0); j++)\n\t\t\t\t{\n\t\t\t\t\tif (!graph.ContainsKey(j))\n\t\t\t\t\t\tgraph[j] = new List<int>();\n\n\t\t\t\t\tif (CheckIfCirclesIntersact(bombs[i][0], bombs[i][1], bombs[j][0], bombs[j][1], bombs[i][2]))\n\t\t\t\t\t\tgraph[i].Add(j);\n\n\t\t\t\t\tif (CheckIfCirclesIntersact(bombs[j][0], bombs[j][1], bombs[i][0], bombs[i][1], bombs[j][2]))\n\t\t\t\t\t\tgraph[j].Add(i);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < bombs.GetLength(0); i++)\n\t\t\t{\n\t\t\t\tHashSet<int> set = new HashSet<int>() { i };\n\t\t\t\tBFS(graph, i, set);\n\t\t\t\tmax = Math.Max(max, set.Count);\n\t\t\t}\n\n\t\t\treturn max;\n\t\t}\n\n\t\tprivate void BFS(Dictionary<int, List<int>> graph, int idx, HashSet<int> set)\n\t\t{\n\t\t\tQueue<int> queue = new Queue<int>();\n\n\t\t\tqueue.Enqueue(idx);\n\n\t\t\twhile (queue.Count > 0)\n\t\t\t{\n\t\t\t\tint node = queue.Dequeue();\n\n\t\t\t\tforeach (var n in graph[node])\n\t\t\t\t{\n\t\t\t\t\tif (!set.Contains(n))\n\t\t\t\t\t{\n\t\t\t\t\t\tqueue.Enqueue(n);\n\t\t\t\t\t\tset.Add(n);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprivate bool CheckIfCirclesIntersact(int x1, int y1, int x2, int y2, int r1)\n\t\t{\n\t\t\tlong dx = x1 - x2;\n\t\t\tlong dy = y1 - y2;\n\t\t\tlong radius = r1;\n\n\t\t\tlong distSq = (dx * dx) + (dy * dy);\n\t\t\tlong radSumSq = radius * radius;\n\n\t\t\treturn distSq <= radSumSq;\n\t\t}\n\t}
2
0
['Breadth-First Search', 'Graph']
0
detonate-the-maximum-bombs
Java DFS with memorization, faster than 97%
java-dfs-with-memorization-faster-than-9-bkil
Basic idea is simmilar to highest voted posts, just optimized a little with caching.\nHere I used a Set for marking visited for simplicity and it can also be re
shibainulol
NORMAL
2022-02-24T00:21:36.004792+00:00
2022-02-24T00:21:36.004823+00:00
153
false
Basic idea is simmilar to highest voted posts, just optimized a little with caching.\nHere I used a Set for marking visited for simplicity and it can also be reused later, since it contains info about all bombs that will explode if we start at bomb[i].\n\n````\nclass Solution {\n public int maximumDetonation(int[][] bombs) {\n int n = bombs.length;\n int res = 0;\n Map<Integer, Set<Integer>> cache = new HashMap<>(); \n for (int i = 0; i < n; i++) {\n Set<Integer> exploded = new HashSet<>(); \n dfs(i, bombs, exploded, cache);\n cache.put(i, exploded);\n res = Math.max(res, exploded.size());\n }\n \n return res;\n }\n \n private void dfs(int current, int[][] bombs, Set<Integer> visited, Map<Integer, Set<Integer>> cache) {\n if (cache.containsKey(current)) {\n visited.addAll(cache.get(current));\n return;\n }\n \n visited.add(current);\n int n = bombs.length;\n for (int i = 0; i < n; i++) {\n if (!visited.contains(i) && inRange(bombs[current], bombs[i])) {\n visited.add(i);\n dfs(i, bombs, visited, cache);\n }\n }\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}\n````
2
0
[]
2
detonate-the-maximum-bombs
Simple C++ code | Both BFS and DFS Approaches
simple-c-code-both-bfs-and-dfs-approache-2k3y
1. DFS Approach : \n\n\n// DFS Approach : ---------->\nclass Solution {\npublic:\n \n // find if point p2(x2,y2) will be inside the circle of point p1(x1,
HustlerNitin
NORMAL
2022-02-11T11:54:06.668559+00:00
2022-02-11T11:54:06.668592+00:00
155
false
**1. DFS Approach :** \n```\n\n// DFS Approach : ---------->\nclass Solution {\npublic:\n \n // find if point p2(x2,y2) will be inside the circle of point p1(x1,y1) \n bool insideCircle(int x1, int y1, int r, int x2, int y2){\n\t // euclidean distance\n int dist = ceil(sqrt( pow(abs(x2-x1),2) + pow(abs(y2-y1),2) ));\n \n return (dist <= r);\n }\n \n int dfs(unordered_map<int, vector<int>>&mp, int src, vector<int>&vis)\n {\n int count=1;\n vis[src] = 1;\n for(auto nbr : mp[src])\n {\n if(vis[nbr]==0){\n \n vis[nbr]=1;\n count+=dfs(mp, nbr, vis);\n }\n \n }\n return count;\n }\n \n // based on number of connected components = number of islands problem\n int maximumDetonation(vector<vector<int>>& bombs) {\n \n // first of all we need to make a undirected (bidirectional) graph\n int n=bombs.size();\n unordered_map<int, vector<int>>g;\n for(int i=0;i<n;i++) // for all center points of circle\n {\n int x1 = bombs[i][0];\n int y1 = bombs[i][1];\n int r = bombs[i][2];\n for(int j=0;j<n;j++)\n { \n if(j != i)\n {\n // we need to check it is in the range\n if(insideCircle(x1, y1, r, bombs[j][0], bombs[j][1]))\n {\n g[i].push_back(j);\n }\n }\n }\n }\n \n int maxbombs=0;\n for(int i=0;i<n;i++) // har ek point se check karenge ki konse bomb se maximum bombs detonate honge \n {\n vector<int>vis(n, 0);\n int count = dfs(g, i, vis);\n maxbombs = max(maxbombs,count);\n }\n return maxbombs;\n }\n};\n```\n\n**2. BFS Approach :**\n```\n\n// BFS Approach : -------->\nclass Solution {\npublic:\n \n // find if point p2(x2,y2) will be inside the circle of point p1(x1,y1) \n bool insideCircle(int x1, int y1, int r, int x2, int y2){\n\t // euclidean distance\n int dist = ceil(sqrt( pow(abs(x2-x1),2) + pow(abs(y2-y1),2) ));\n \n return (dist <= r);\n }\n \n int bfs(unordered_map<int, vector<int>>&mp, int src, vector<int>&vis)\n {\n queue<int>q;\n q.push(src);\n vis[src] = 1;\n \n int count = 0;\n while(!q.empty())\n {\n auto curr = q.front();\n q.pop();\n count++;\n for(auto nbr : mp[curr])\n {\n if(vis[nbr] == 0){\n \n vis[nbr] = 1;\n q.push(nbr);\n }\n }\n }\n return count;\n }\n \n // based on number of connected components = number of islands problem\n int maximumDetonation(vector<vector<int>>& bombs) {\n \n // first of all we need to make a undirected (bidirectional) graph\n int n=bombs.size();\n unordered_map<int, vector<int>>g;\n for(int i=0;i<n;i++) // for all center points of circle\n {\n int x1 = bombs[i][0];\n int y1 = bombs[i][1];\n int r = bombs[i][2];\n for(int j=0;j<n;j++)\n { \n if(j != i)\n {\n // we need to check it is in the range\n if(insideCircle(x1, y1, r, bombs[j][0], bombs[j][1]))\n {\n g[i].push_back(j);\n }\n }\n }\n }\n \n int maxbombs=0;\n for(int i=0;i<n;i++) // har ek point se check karenge ki konse bomb se maximum bombs detonate honge \n {\n vector<int>vis(n, 0);\n int count = bfs(g, i, vis);\n maxbombs = max(maxbombs, count);\n }\n return maxbombs;\n }\n};\n```\n**if you like my approach please don\'t forget to hit upvote button ! : )**
2
1
['C', 'C++']
0
lexicographically-smallest-palindrome
[Java/C++/Python] Two Pointers
javacpython-two-pointers-by-lee215-oay0
Explanation\nCompare each s[i] with its symmetrical postion in palindrome,\nwhich is s[n - 1 - i].\n\nTo make the lexicographically smallest palindrome,\nwe mak
lee215
NORMAL
2023-05-21T04:01:48.905500+00:00
2023-05-21T04:01:48.905548+00:00
3,936
false
# **Explanation**\nCompare each `s[i]` with its symmetrical postion in palindrome,\nwhich is `s[n - 1 - i]`.\n\nTo make the lexicographically smallest palindrome,\nwe make `s[i] = s[n - 1 - i] = min(s[i], s[n - i - 1])`\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(n)`\n<br>\n\n**Java**\n```java\n public String makeSmallestPalindrome(String s) {\n int n = s.length();\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < n; i++)\n sb.append(Character.toString(Math.min(s.charAt(i), s.charAt(n - i - 1))));\n return sb.toString();\n }\n```\n\n**C++**\n```cpp\n string makeSmallestPalindrome(string s) {\n int n = s.size();\n for (int i = 0; i < n; ++i)\n s[i] = s[n - 1 - i] = min(s[i], s[n - i - 1]);\n return s;\n }\n```\n\n**Python**\n```py\n def makeSmallestPalindrome(self, s: str) -> str:\n return \'\'.join(map(min, zip(s, s[::-1])))\n```\n
50
0
['C', 'Python', 'Java']
4
lexicographically-smallest-palindrome
Python Elegant & Short | O(n) | 4 Lines
python-elegant-short-on-4-lines-by-kyryl-vf5h
Complexity\n- Time complexity: O(n)\n- Space complexity: O(n)\n\n# Code\n\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n letter
Kyrylo-Ktl
NORMAL
2023-05-21T16:26:32.453582+00:00
2023-05-21T16:26:32.453618+00:00
1,490
false
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n letters = list(s)\n\n for i in range(len(s) // 2):\n letters[i] = letters[~i] = min(letters[i], letters[~i])\n\n return \'\'.join(letters)\n\n```
17
0
['Python', 'Python3']
0
lexicographically-smallest-palindrome
Java | Easy solution | 8 lines
java-easy-solution-8-lines-by-judgementd-ita9
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-05-21T04:01:47.176242+00:00
2023-05-21T04:04:34.868753+00:00
2,061
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)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n var c = s.toCharArray();\n int i = 0, j = c.length - 1;\n \n while (i < j) {\n if (c[i] < c [j])\n c[j--] = c[i++];\n else\n c[i++] = c[j--];\n }\n return new String(c);\n }\n}\n```\nIf you like my solution, please upvote it!
16
1
['Java']
2
lexicographically-smallest-palindrome
Take min || Very simple and easy to understand solution
take-min-very-simple-and-easy-to-underst-rv5e
Up vote if this solution helps\n# Approach\nTake two iterator one from front and one from back.\nThen take the min of s(front) & s(back) and set both s(front)
kreakEmp
NORMAL
2023-05-21T04:04:17.946790+00:00
2023-05-21T04:56:10.212035+00:00
2,560
false
<b> Up vote if this solution helps</b>\n# Approach\nTake two iterator one from front and one from back.\nThen take the min of s(front) & s(back) and set both s(front) and s(back) to the min value.\n \n# Code\n```\n string makeSmallestPalindrome(string s) {\n int front = 0, back = s.size()-1;\n while(front <= s.size()/2){\n s[front] = min(s[front], s[back]);\n s[back] = s[front];\n front++; back--;\n }\n return s;\n }\n```\n\n<b>Here is an article of my last interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted
14
1
['C++']
4
lexicographically-smallest-palindrome
Python 3 || 4 lines, w/ explanation an example || T/S: 58% / 72%
python-3-4-lines-w-explanation-an-exampl-847r
\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str: # Example: s = \'sdnvnfe\'\n\n ans, n = list(s), len(s)
Spaulding_
NORMAL
2023-05-21T17:25:08.397632+00:00
2024-06-20T19:18:41.140726+00:00
1,089
false
```\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str: # Example: s = \'sdnvnfe\'\n\n ans, n = list(s), len(s) # n = 7 , n//2 = 3\n # ans = [s, d, n, v, n, f, e]\n for i in range(n//2): \n # i = 0: ans = [|e| ,d,n,v,n,f, |e|]\n ans[i]=ans[n-i-1] = min(ans[i],ans[n-i-1]) # i = 1: ans = [e,|d|, n,v,n, |d|,e] \n # i = 2: ans = [e,d,|n|, v, |n|,d,e]\n \n return \'\'.join(ans) # return ().join([e,d,n,v,n,d,e]) = \'ednvnde\'\n```\n[https://leetcode.com/problems/lexicographically-smallest-palindrome/submissions/1294942680/](https://leetcode.com/problems/lexicographically-smallest-palindrome/submissions/1294942680/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~`len(s)`.\n
13
0
['Python3']
1
lexicographically-smallest-palindrome
✔💯 DAY 416 | TWO pointers | 0ms 100% | | [PYTHON/JAVA/C++] | EXPLAINED 🆙🆙🆙
day-416-two-pointers-0ms-100-pythonjavac-ez94
Intuition & Approach\n Describe your approach to solving the problem. \n##### \u2022\tThe string is converted to a char array so that the characters can be acce
ManojKumarPatnaik
NORMAL
2023-05-21T04:01:59.985541+00:00
2023-05-21T04:14:22.978269+00:00
1,522
false
# Intuition & Approach\n<!-- Describe your approach to solving the problem. -->\n##### \u2022\tThe string is converted to a char array so that the characters can be accessed more easily.\n##### \u2022\tTwo pointers are initialized to the beginning and end of the array.\n##### \u2022\tA variable is initialized to keep track of the number of operations performed.\n##### \u2022\tThe loop iterates until the left pointer reaches the right pointer.\n##### \u2022\tInside the loop, the characters at the left and right pointers are compared.\n##### \u2022\tIf the characters are not equal, then the smaller character is swapped with the larger character.\n##### \u2022\tThe number of operations is incremented by 1.\n##### \u2022\tIf the number of operations is 0, then the original string is returned.\n##### \u2022\tOtherwise, a new string is created from the char array and returned.\n\n\n\n# Complexity\n- Time complexity:o(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n char[] arr = s.toCharArray();\n int left = 0, right = arr.length - 1;\n int ops = 0;\n while (left < right) {\n if (arr[left] != arr[right]) {\n if (arr[left] > arr[right]) {\n arr[left] = arr[right];\n } else {\n arr[right] = arr[left];\n }\n ops++;\n }\n left++;\n right--;\n }\n if (ops == 0) {\n return s;\n }\n return new String(arr);\n}\n}\n```\n# C++ \n```C++ \nstring makeSmallestPalindrome(string s) {\n char arr[s.length()];\n for (int i = 0; i < s.length(); i++) {\n arr[i] = s[i];\n }\n\n int left = 0, right = s.length() - 1;\n int ops = 0;\n while (left < right) {\n if (arr[left] != arr[right]) {\n if (arr[left] > arr[right]) {\n arr[left] = arr[right];\n } else {\n arr[right] = arr[left];\n }\n ops++;\n }\n left++;\n right--;\n }\n\n if (ops == 0) {\n return s;\n }\n\n string result = "";\n for (int i = 0; i < s.length(); i++) {\n result += arr[i];\n }\n\n return result;\n}\n\n```\n# PY \n\n```\ndef make_smallest_palindrome(s):\n arr = list(s)\n left = 0\n right = len(arr) - 1\n ops = 0\n while left < right:\n if arr[left] != arr[right]:\n if arr[left] > arr[right]:\n arr[left] = arr[right]\n else:\n arr[right] = arr[left]\n ops += 1\n left += 1\n right -= 1\n\n if ops == 0:\n return s\n\n result = ""\n for i in arr:\n result += i\n\n return result\n```\n\n\n![BREUSELEE.webp](https://assets.leetcode.com/users/images/8bb0ed4d-d998-4778-8a6b-30bc8e97edfa_1684321488.7915804.webp)\n\n\n![meme2.png](https://assets.leetcode.com/users/images/d588f492-3f95-45f6-8e4a-10d6069002a5_1680054021.7117147.png)\n\nPlease Upvote\uD83D\uDC4D\uD83D\uDC4D\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n\u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06
13
0
['Two Pointers', 'Python', 'C++', 'Java', 'Python3']
2
lexicographically-smallest-palindrome
C++ || TWO POINTER || EASY TO UNDERSTAND
c-two-pointer-easy-to-understand-by-gane-bion
\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\n// <!-- UPVOTE IF THIS CODE IS HELP FULL FOR YOU\n// IF ANY SUGGETION YOU CAN
ganeshkumawat8740
NORMAL
2023-05-21T04:28:02.001411+00:00
2023-05-21T05:11:50.421420+00:00
1,395
false
\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n// <!-- UPVOTE IF THIS CODE IS HELP FULL FOR YOU\n// IF ANY SUGGETION YOU CAN COMMENT HERE. -->\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int i = 0, j = s.length()-1;//make pointer index\n while(i<j){\n if(s[i] != s[j]){\n s[i] = s[j] = min(s[i],s[j]);//initialise i and j to min of (s[i],s[j]);\n }\n i++;j--;\n }\n return s;\n }\n};\n```
10
0
['Two Pointers', 'C++']
1
lexicographically-smallest-palindrome
|| in java
in-java-by-2manas1-mq9l
Intuition\n Describe your first thoughts on how to solve this problem. \n\nRemoved the use of StringBuilder s1, as it was not necessary for the task. Instead, I
2manas1
NORMAL
2023-08-11T14:33:08.309541+00:00
2023-08-11T14:33:08.309575+00:00
145
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nRemoved the use of StringBuilder s1, as it was not necessary for the task. Instead, I directly manipulated the char array ch.\nRemoved the unnecessary sorting of s1, as you only need to replace characters with the smaller of the two.\nUsed (char) Math.min(ch[i], ch[j]) to determine the smaller character between ch[i] and ch[j].\nChanged the loop condition to i < j to properly compare and replace characters.\nThis corrected code should now correctly modify the given string s to create the smallest palindrome possible by replacing characters.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n char[] ch = s.toCharArray();\n\n for (int i = 0, j = ch.length - 1; i < j; i++, j--) {\n if (ch[i] != ch[j]) {\n char smallerChar = (char) Math.min(ch[i], ch[j]);\n ch[i] = smallerChar;\n ch[j] = smallerChar;\n }\n }\n\n return new String(ch);\n }\n}\n\n```
5
0
['Java']
0
lexicographically-smallest-palindrome
✅[Python] Simple and Clean, beats 88%✅
python-simple-and-clean-beats-88-by-_tan-erp5
Please upvote if you find this helpful. \u270C\n\n\nThis is an NFT\n\n# Intuition\nThe problem asks us to modify a given string s by performing operations on it
_Tanmay
NORMAL
2023-05-29T07:56:04.687662+00:00
2023-05-29T07:56:04.687703+00:00
467
false
### Please upvote if you find this helpful. \u270C\n<img src="https://assets.leetcode.com/users/images/b8e25620-d320-420a-ae09-94c7453bd033_1678818986.7001078.jpeg" alt="Cute Robot - Stable diffusion" width="200"/>\n\n*This is an NFT*\n\n# Intuition\nThe problem asks us to modify a given string `s` by performing operations on it. In one operation, we can replace a character in `s` with another lowercase English letter. Our task is to make `s` a palindrome with the minimum number of operations possible. If there are multiple palindromes that can be made using the minimum number of operations, we should make the lexicographically smallest one.\n\n# Approach\n1. Convert the string `s` into a list of characters `s_list`.\n\n2. Initialize two pointers `l` and `r` at the start and end of the list respectively.\n\n3. Enter a while loop that runs until `l` is greater than or equal to `r`.\n\n4. Inside the loop, check if the character at index `l` is smaller than the character at index `r`. \n\n1. If it is, replace the character at index `r` with the character at index `l`.\n\n1. If the character at index `l` is greater than the character at index `r`, replace the character at index `l` with the character at index `r`.\n\n1. Increment `l` by 1 and decrement `r` by 1.\n\n1. After the loop ends, join the list back into a new string `new_s` and return it.\n\n# Complexity\n- Time complexity: $$O(n)$$ where n is the length of string s.\n- Space complexity: $$O(n)$$ where n is the length of string s.\n\n# Code\n```\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n s_list = list(s)\n l,r = 0, len(s_list)-1\n while l<r:\n if ord(s_list[l]) < ord(s_list[r]):\n s_list[r] = s_list[l]\n elif ord(s_list[l]) > ord(s_list[r]):\n s_list[l] = s_list[r]\n l+=1\n r-=1\n new_s = \'\'.join(s_list)\n return new_s \n```
4
0
['Two Pointers', 'String', 'Python', 'Python3']
0
lexicographically-smallest-palindrome
Python3, Two Lines, Use Smaller characters
python3-two-lines-use-smaller-characters-jr0p
Intuition\nWe are checking pairs of characters: s[i] and s[-i-1] and replace them with the lexicograficaly smaller one of them.\n\n# Complexity\n- Time complexi
silvia42
NORMAL
2023-05-21T04:39:19.970508+00:00
2023-05-21T04:41:00.764962+00:00
986
false
# Intuition\nWe are checking pairs of characters: `s[i]` and `s[-i-1]` and replace them with the lexicograficaly smaller one of them.\n\n# Complexity\n- Time complexity:\n`O(N)`\n\n- Space complexity:\n`O(N)`\n\n# Code\n```\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n pal=\'\'.join([min(a,b) for a,b in zip(s[:len(s)//2],s[::-1])])\n return pal + s[len(s)//2]*(len(s)%2) + pal[::-1]\n```\n# Code explanation in Python\n```\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n n=len(s)\n pal=\'\'\n for a,b in zip(s[:n//2],s[::-1]):\n pal+=min(a,b)\n return pal + s[n//2]*(n%2) + pal[::-1]\n```
4
0
['Python3']
0
lexicographically-smallest-palindrome
c++ solution || easy to understand
c-solution-easy-to-understand-by-harshil-i5f5
Code\n\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int left = 0;\n int right = s.length() - 1;\n\n while (l
harshil_sutariya
NORMAL
2023-05-21T04:03:45.328823+00:00
2023-05-21T04:03:45.328852+00:00
952
false
# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int left = 0;\n int right = s.length() - 1;\n\n while (left < right) {\n if (s[left] != s[right]) {\n string modified1 = s;\n modified1[right] = s[left];\n\n std::string modified2 = s;\n modified2[left] = s[right];\n\n if (modified1 < modified2) {\n s = modified1;\n } else {\n s = modified2;\n }\n }\n\n left++;\n right--;\n }\n\n return s;\n }\n};\n\n\n```
4
0
['C++']
1
lexicographically-smallest-palindrome
Easy cpp solution
easy-cpp-solution-by-inderjeet09-htvs
\n\n# Code\n\n#include <string>\n#include <algorithm>\n\nclass Solution {\npublic:\n string makeSmallestPalindrome(string str) {\n int start = 0;\n
inderjeet09
NORMAL
2023-05-21T04:02:39.429652+00:00
2023-05-21T04:02:39.429686+00:00
50
false
\n\n# Code\n```\n#include <string>\n#include <algorithm>\n\nclass Solution {\npublic:\n string makeSmallestPalindrome(string str) {\n int start = 0;\n int end = str.length() - 1;\n char ch[str.length()];\n copy(str.begin(), str.end(), ch);\n \n while (start <= end) {\n if (ch[start] == ch[end]) {\n start++;\n end--;\n } else {\n int inder = ch[start] - \'0\';\n int jeet = ch[end] - \'0\';\n if (inder > jeet) {\n ch[start] = ch[end];\n } else {\n ch[end] = ch[start];\n }\n \n start++;\n end--;\n }\n }\n \n return string(ch, str.length());\n }\n};\n\n```
4
0
['C++']
0
lexicographically-smallest-palindrome
SIMPLE TWO-POINTER C++ SOLUTION
simple-two-pointer-c-solution-by-jeffrin-p1iz
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
Jeffrin2005
NORMAL
2024-07-19T12:46:45.976205+00:00
2024-08-12T17:10:32.239754+00:00
175
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)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int left = 0;\n int right = s.size() - 1;\n\n while (left < right) {\n if (s[left] != s[right]) {\n // Replace the character at the larger index with the smaller one\n if (s[left] > s[right]) {\n s[left] = s[right]; // Make the change towards the lexicographically smaller character\n } else {\n s[right] = s[left];\n }\n }\n left++;\n right--;\n }\n\n return s;\n }\n};\n```
3
0
['C++']
0
lexicographically-smallest-palindrome
Lexicographically Smallest Palindrome (JavaScript | Two Pointers)
lexicographically-smallest-palindrome-ja-9w4p
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n\n/**\n * @param {string} s\n * @return {string}\n */\nvar makeSmallestPalindrome =
TheCodeLord
NORMAL
2024-04-10T01:04:07.594046+00:00
2024-04-10T01:04:07.594074+00:00
61
false
# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\n/**\n * @param {string} s\n * @return {string}\n */\nvar makeSmallestPalindrome = function(s) {\n let left = 0;\n let right = s.length - 1;\n let str = s.split(\'\');\n\n while(left < right) {\n if(str[left] !== str[right]) {\n if (str[left] < str[right]) {\n str[right] = str[left];\n } else {\n str[left] = str[right];\n }\n }\n left++;\n right--;\n }\n\n return str.join(\'\');\n};\n```
3
0
['Two Pointers', 'JavaScript']
0
lexicographically-smallest-palindrome
Easy to Understand Java Code || Beats 100%
easy-to-understand-java-code-beats-100-b-4y0d
Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n# Code\n\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n char[
Saurabh_Mishra06
NORMAL
2024-04-08T03:26:04.987994+00:00
2024-04-08T03:26:04.988039+00:00
373
false
# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n char[] c = s.toCharArray();\n int i = 0, j = s.length()-1;\n\n while(i < j){\n if(c[i] <c[j]){\n c[j--] = c[i++];\n }else {\n c[i++] = c[j--];\n }\n }\n return new String(c);\n }\n}\n```
3
0
['Java']
1
lexicographically-smallest-palindrome
Simple - Easy to Understand Solution || Beats - 100%
simple-easy-to-understand-solution-beats-73t9
\n\n# Code\n\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n char str[] = s.toCharArray();\n int i=0, j=s.length()-1;\n
tauqueeralam42
NORMAL
2023-07-17T09:16:49.586100+00:00
2023-07-17T09:16:49.586125+00:00
314
false
\n\n# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n char str[] = s.toCharArray();\n int i=0, j=s.length()-1;\n while(i<j){\n str[i] = (char)Math.min(str[i],str[j]);\n str[j]= str[i];\n i++;\n j--;\n }\n return new String(str);\n \n }\n}\n```
3
0
['Two Pointers', 'String', 'C++', 'Java']
1
lexicographically-smallest-palindrome
Transform
transform-by-votrubac-22sd
C++\ncpp\nstring makeSmallestPalindrome(string s) {\n transform(begin(s), end(s), rbegin(s), begin(s), [](char a, char b){\n return min(a, b);\n })
votrubac
NORMAL
2023-05-24T20:20:35.528265+00:00
2023-05-24T20:20:35.528300+00:00
166
false
**C++**\n```cpp\nstring makeSmallestPalindrome(string s) {\n transform(begin(s), end(s), rbegin(s), begin(s), [](char a, char b){\n return min(a, b);\n });\n return s;\n}\n```
3
0
['C']
1
lexicographically-smallest-palindrome
Python3 Solution
python3-solution-by-motaharozzaman1996-m431
\n\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n return \'\'.join(map(min,zip(s,s[::-1])))\n
Motaharozzaman1996
NORMAL
2023-05-22T01:30:15.063773+00:00
2023-05-22T01:30:15.063811+00:00
292
false
\n```\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n return \'\'.join(map(min,zip(s,s[::-1])))\n```
3
0
['Python', 'Python3']
0
lexicographically-smallest-palindrome
Diagram & Image Explaination🥇 C++ Full Optimized🔥2 PTR | Well Explained
diagram-image-explaination-c-full-optimi-an8m
Diagram\n Describe your first thoughts on how to solve this problem. \n\n\n\n# Approach\n Describe your approach to solving the problem. \nint i=0,j=s.length()-
7mm
NORMAL
2023-05-21T06:38:00.973777+00:00
2023-05-21T06:38:00.973819+00:00
322
false
# Diagram\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n![code2flow_Gk6T30 (1).png](https://assets.leetcode.com/users/images/ae1522d1-3dc8-4459-981b-2f2ae9f9a7b2_1684650906.2661316.png)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nint i=0,j=s.length()-1;: Initialize two variables i and j to the start and end indices of the string respectively.\n\nwhile(i<j): While the indices i and j don\'t cross each other, do the following:\n\nif(s[i]>s[j]): If the character at index i is greater than the character at index j, then replace the character at index i with the character at index j.\n\ns[i]=s[j];\n\nIncrement i and decrement j.\n\ni++;\nj--;\nelse: If the character at index i is less than or equal to the character at index j, then replace the character at index j with the character at index i.\n\ns[j]=s[i];\n\nIncrement i and decrement j.\n\ni++;\nj--;\nreturn s;: Return the modified string.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int i=0,j=s.length()-1;\n while(i<j)\n {\n if(s[i]>s[j])\n {\n s[i]=s[j];\n \n i++;\n j--;\n }\n else\n {\n s[j]=s[i];\n i++;\n j--;\n }\n }return s;\n \n }\n};\n```\n![7abc56.jpg](https://assets.leetcode.com/users/images/275376dd-1a0c-4d7a-9d8e-1e79bdf27056_1684651072.6219082.jpeg)\n
3
0
['String', 'String Matching', 'C++']
1
lexicographically-smallest-palindrome
Two Pointers | C++
two-pointers-c-by-tusharbhart-cehe
\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int l = 0, r = s.size() - 1;\n while(l < r) {\n if(s[l] !=
TusharBhart
NORMAL
2023-05-21T04:04:53.727734+00:00
2023-05-21T04:04:53.727779+00:00
590
false
```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int l = 0, r = s.size() - 1;\n while(l < r) {\n if(s[l] != s[r]) {\n char c = min(s[l], s[r]);\n s[l] = s[r] = c;\n }\n l++, r--;\n }\n return s;\n }\n};\n```
3
0
['Two Pointers', 'C++']
0
lexicographically-smallest-palindrome
Easy Java Solution
easy-java-solution-by-codehunter01-gzty
Approach\n Describe your approach to solving the problem. \nJust check forward and Backword elements are equal or Not. If Not then change bigger one to smaller
codeHunter01
NORMAL
2023-05-21T04:04:17.328788+00:00
2023-05-22T12:45:15.824215+00:00
816
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nJust check forward and Backword elements are equal or Not. If Not then change bigger one to smaller one.\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n int n = s.length();\n char[] str = new char[n];\n for(int i=0;i<n;i++)\n {\n str[i] = s.charAt(i);\n }\n for(int i=0;i<n/2;i++)\n {\n if(str[i]!=str[n-i-1])\n {\n if((str[i]-\'a\')<(str[n-i-1]-\'a\'))\n {\n str[n-i-1] = str[i];\n }\n else\n str[i] = str[n-i-1];\n }\n }\n String st ="";\n for(int i=0;i<n;i++)\n st+=str[i];\n return st;\n }\n}\n```
3
0
['String', 'Java']
0
lexicographically-smallest-palindrome
Short || Clean || Simple || Java Solution
short-clean-simple-java-solution-by-hima-g747
\njava []\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n for(int i=0; i<s.length()/2; i++){\n char c = (char)Math.m
HimanshuBhoir
NORMAL
2023-05-21T04:02:04.975301+00:00
2023-05-21T04:29:56.643585+00:00
2,505
false
\n```java []\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n for(int i=0; i<s.length()/2; i++){\n char c = (char)Math.min((int)s.charAt(i),(int)s.charAt(s.length()-1-i));\n s = s.substring(0,i) + c + s.substring(i+1,s.length()-i-1) + c + s.substring(s.length()-i);\n }\n return s;\n }\n}\n```
3
0
['Java']
5
lexicographically-smallest-palindrome
C++ ✅ || EASY ✅ || 3 Lines
c-easy-3-lines-by-dheeraj3220-lqd4
\n<<<<UpVote\n\n\n\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int i=0,j=s.size()-1;\n while(i<j){\n
Dheeraj3220
NORMAL
2023-05-21T04:01:00.834506+00:00
2023-05-21T04:08:36.282301+00:00
388
false
\n**<<<<UpVote**\n\n\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int i=0,j=s.size()-1;\n while(i<j){\n if(s[i]<s[j]) s[j--]=s[i++];\n else s[i++]=s[j--];\n }\n return s;\n }\n};\n```
3
0
['Two Pointers', 'C']
1
lexicographically-smallest-palindrome
⬆️🆙✅ Easy to understand & Best solution || 💯 Beats 100% of users with Java || O(n)💥👏🔥
up-easy-to-understand-best-solution-beat-8o1m
Please upvote if my solution and efforts helped you.\n***\n\n\n## Approach - 2 Pointers Method\n1 pointer (i) from starting of the string\nanother pointer (j) f
SumitMittal
NORMAL
2024-06-09T16:35:43.095669+00:00
2024-06-09T16:35:43.095692+00:00
58
false
# Please upvote if my solution and efforts helped you.\n***\n![proof.png](https://assets.leetcode.com/users/images/9a3165aa-00b4-470a-affd-9e55e2a472e6_1717950665.4987402.png)\n\n## Approach - 2 Pointers Method\n1 pointer (i) from starting of the string\nanother pointer (j) from the last of the string\nPut minimum element at the ith index and copy same value at the jth index.\n\n## Complexity\n- Time complexity:\n The time complexity is O(n). Because we are traversing the input string only once and till half length.\n\n- Space complexity:\nThe space complexity is O(n) because we are using char array of the string length size and a constant amount of space to store our variables, regardless of the size of the input array.\n\n## Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n char charArr[] = s.toCharArray();\n int i = 0, j = s.length() - 1;\n while (i < j) {\n charArr[i] = (char) Math.min(charArr[i], charArr[j]);\n charArr[j] = charArr[i];\n i++;\n j--;\n }\n return new String(charArr);\n }\n}\n```\n![Leetcode-upvote.jpeg](https://assets.leetcode.com/users/images/e8c05dce-1b84-48c6-a2e9-0000f34b3c4b_1717950791.395676.jpeg)\n
2
0
['Array', 'Two Pointers', 'String', 'Java']
0
lexicographically-smallest-palindrome
Easy JavaScript solution
easy-javascript-solution-by-navyatjacob-8cyy
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
navyatjacob
NORMAL
2024-02-05T12:32:51.961152+00:00
2024-02-05T12:32:51.961170+00:00
65
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} s\n * @return {string}\n */\n\nvar makeSmallestPalindrome = function(s) {\n let count=0;\n let arr=s.split(\'\')\n let i=0,len=arr.length-1\n let reversed=arr.slice().reverse()\n while(i<=len && arr!=reversed){\n if(arr[i]==arr[len]){}\n else if(arr[i].charCodeAt(0)>arr[len].charCodeAt(0)){\n arr[i]=arr[len]\n count++\n }\n else if(arr[i].charCodeAt(0)<arr[len].charCodeAt(0)){\n arr[len]=arr[i]\n count++\n }i++;len--; }\n return arr.join(\'\')};\n```
2
0
['JavaScript']
0
lexicographically-smallest-palindrome
97 ms
97-ms-by-satvik_yewale-1qes
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
Satvik_Yewale
NORMAL
2023-12-18T19:11:55.179331+00:00
2023-12-18T19:11:55.179360+00:00
19
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(object):\n def makeSmallestPalindrome(self, s):\n """\n :type s: str\n :rtype: str\n """\n s = list(s)\n l = len(s)\n for i in range(l // 2):\n a = s[i]\n b = s[l-1-i]\n\n if ord(a) >= ord(b):\n s[i] = b\n else:\n s[l-1-i] = a\n return "".join(s)\n```
2
0
['Python']
0
lexicographically-smallest-palindrome
Beginner-friendly || Simple solution with Two Pointer in Python3 / TypeScript
beginner-friendly-simple-solution-with-t-juh0
Intuition\nLet\'s briefly explain what the problem is:\n- there\'s a string s with lowercase English letters\n- our goal is to modify s to be the lexicographica
subscriber6436
NORMAL
2023-10-23T17:56:28.807623+00:00
2024-01-11T04:42:35.429332+00:00
211
false
# Intuition\nLet\'s briefly explain what the problem is:\n- there\'s a string `s` with lowercase English letters\n- our goal is to modify `s` to be **the lexicographically smallest palindrome**\n\n**A palindrome** is a string, when an original word is equal to its **reversed version**.\nThe simplest way to build this palindrome is to set **Two Pointers** opposite to each other, compare particular letters and use **the lexicographically smallest one**.\n\n```\n# Example\n\ns = \'aecab\'\n# i = 0, j = 4 => a < b, (a)eca(a)\n# i = 1, j = 3 => e > a, a(a)c(a)a\n# The lexicographically smallest palindrome is \'aacaa\'\n```\n\n# Approach\n1. declare `ans` to store letters\n2. iterate over **half** of a string with `left` and `right` pointers\n3. check ASCII precedence to find **the lexicographically smallest letter** between `s[left]` and `s[right]`\n4. return `ans` \n\n# Complexity\n- Time complexity: **O(N)** to iterate over `s`\n\n- Space complexity: **O(N)** to store `ans`\n\n# Code in Python3\n```\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n n = len(s)\n ans = [\'\'] * n\n left = 0\n\n for right in range(n - 1, (n - 1) // 2 - 1, -1):\n if s[left] <= s[right]:\n [ans[left], ans[right]] = [s[left], s[left]]\n else: \n [ans[left], ans[right]] = [s[right], s[right]] \n \n left += 1\n\n return "".join(ans)\n```\n# Code in TypeScript\n```\nfunction makeSmallestPalindrome(s: string): string {\n const n = s.length\n const ans = Array(n).fill(\'\')\n\n for (let right = n - 1, left = 0; right >= right / 2; right--, left++) {\n if (s[left] <= s[right]) {\n ans[left] = s[left]\n ans[right] = s[left]\n } else {\n ans[left] = s[right]\n ans[right] = s[right]\n }\n }\n\n return ans.join(\'\')\n};\n```
2
0
['Two Pointers', 'String', 'TypeScript', 'Python3']
1
lexicographically-smallest-palindrome
[JAVA] easy solution 95% faster
java-easy-solution-95-faster-by-jugantar-9x8b
\n\n# Approach\n Describe your approach to solving the problem. \nJust check whether elements are equal in the first half and second half of the string. If not
Jugantar2020
NORMAL
2023-07-19T17:02:42.866416+00:00
2023-07-19T17:02:42.866436+00:00
158
false
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nJust check whether elements are equal in the first half and second half of the string. If not then change lexicographically bigger characters one to smaller ones.\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n var c = s.toCharArray();\n int i = 0, j = c.length - 1;\n\n while(i < j) {\n if(c[i] < c[j])\n c[j --] = c[i ++];\n else\n c[i ++] = c[j --];\n } \n return new String(c);\n }\n}\n```\n# PLEASE UPVOTE IF IT WAS HELPFULL
2
0
['Two Pointers', 'String', 'Java']
0
lexicographically-smallest-palindrome
Simple JAVA Solution for beginners. 9ms. Beats 94.80%.
simple-java-solution-for-beginners-9ms-b-3x77
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
sohaebAhmed
NORMAL
2023-05-27T09:53:01.394076+00:00
2023-05-27T09:53:01.394106+00:00
867
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n char arr[] = s.toCharArray();\n int i = 0;\n int j = arr.length - 1;\n while (i < j) {\n if (arr[i] < arr[j]) {\n arr[j--] = arr[i++];\n } else {\n arr[i++] = arr[j--];\n }\n }\n return new String(arr);\n }\n}\n```
2
0
['Two Pointers', 'String', 'Java']
0