Detonate the Maximum Bombs solution explained

Detonate the Maximum Bombs gives you bombs as (x, y, radius) and asks how many can go off in total if you light exactly one and let the chain reaction run, choosing the best starting bomb. Bomb A sets off bomb B when B's center lies within A's radius, which is a one-way relationship, so model it as a directed graph and run a breadth-first or depth-first search from every bomb. Building the edges is O(n²) and the searches are O(n³) in the worst case, which is the expected solution for this problem.

By Published 10 min read

The problem in plain words

Bombs sit at points on a flat grid. Each one is described by its center x and y and a blast radius r. When a bomb explodes, every other bomb whose center is at a distance of at most r from its center explodes as well, and those explosions spread in the same way. You may light exactly one bomb by hand. Return the largest number of bombs, including the one you lit, that can end up exploding.

Layouts written for this page, each bomb as [x, y, r]
BombsBest answerWhy
[0, 0, 10], [8, 0, 1]2Lighting the big bomb reaches the small one 8 away. Lighting the small one reaches nothing
[0, 0, 3], [2, 0, 1], [5, 0, 2]2The first bomb sets off the second. The third is 5 from the first and 3 from the second, out of reach both ways
[0, 0, 2], [2, 0, 2], [4, 0, 2], [6, 0, 1]4Each of the first three is exactly 2 from the next one, and an exact touch counts, so lighting the first clears the row
[0, 0, 5], [4, 0, 1], [8, 0, 5]2Both large bombs reach the small one between them but not each other. Merging groups both ways would wrongly say 3
Layouts written for this page, each bomb as [x, y, r]. Scroll sideways on a small screen.

The first row is the whole point of the problem. Distance is symmetric, but reach is not, because each bomb has its own radius. If you treat the bombs as an undirected network you will say both starting points give 2, which is wrong for the small bomb.

What the interviewer is looking for

This is a graph problem that never mentions a graph. The interviewer wants to see you turn a geometry story into nodes and edges, notice the edges have a direction, and pick a search you can run from every node. They also listen for two practical details: using integer squared distances instead of floating-point square roots, and the overflow risk when coordinates are large. Candidates who reach for union-find because it worked on Number of Islands are the ones this problem is designed to catch.

When does one bomb set off another?

Bomb i at (xi, yi) with radius ri sets off bomb j at (xj, yj) when the distance between the centers is at most ri. Square both sides to avoid the square root: (xi - xj)² + (yi - yj)² <= ri². Everything stays an integer, and a bomb sitting exactly on the edge of the circle is counted without any rounding trouble. Only ri matters for this edge. Bomb j's own radius decides edges going out of j, not into it.

Brute force: re-sweep until the chain stops

Without any graph, you can simulate directly. For each starting bomb, keep a set of bombs that have gone off. Sweep over every pair (lit bomb, unlit bomb) and light the unlit one if it is in range. Repeat full sweeps until a sweep adds nothing. A sweep is O(n²), and there can be up to n sweeps, so one start costs O(n³) and all starts cost O(n⁴). It is slow, but it follows the story so closely that it makes a useful checker.

def max_detonated_slow(bombs):
    n = len(bombs)
    best = 0
    for start in range(n):
        lit = {start}
        grew = True
        while grew:                      # keep sweeping until nothing new goes off
            grew = False
            for i in list(lit):
                xi, yi, ri = bombs[i]
                for j, (xj, yj, _) in enumerate(bombs):
                    if j not in lit and (xi - xj) ** 2 + (yi - yj) ** 2 <= ri * ri:
                        lit.add(j)
                        grew = True
        best = max(best, len(lit))
    return best
Python: simulate from each start by repeating sweeps. O(n⁴), used as a checker.

The graph solution

The brute force keeps rechecking the same pairs. Do that work once instead: compute, for every bomb, the list of bombs it sets off directly. That is a directed adjacency list built in O(n²). Now the chain reaction from a start is just the set of nodes reachable from it, which a breadth-first or depth-first search finds in O(n + E), where E is the number of edges. Run a search from every bomb and keep the largest count.

from collections import deque

def max_detonated(bombs):
    n = len(bombs)
    # reach[i] lists every bomb that bomb i sets off directly.
    reach = [[] for _ in range(n)]
    for i, (xi, yi, ri) in enumerate(bombs):
        for j, (xj, yj, _) in enumerate(bombs):
            if i != j and (xi - xj) ** 2 + (yi - yj) ** 2 <= ri * ri:
                reach[i].append(j)

    best = 0
    for start in range(n):
        seen = [False] * n
        seen[start] = True
        queue = deque([start])
        count = 1
        while queue:
            for j in reach[queue.popleft()]:
                if not seen[j]:
                    seen[j] = True
                    count += 1
                    queue.append(j)
        best = max(best, count)
        if best == n:                    # cannot do better than every bomb
            break
    return best
Python: build directed edges once, then a breadth-first search from each bomb

The early exit is a small touch interviewers like: once some start reaches every bomb, no other start can beat it. Python integers never overflow, so the squared distance is safe whatever the coordinates are.

function maxDetonated(bombs) {
  const n = bombs.length;
  const reach = Array.from({ length: n }, () => []);
  for (let i = 0; i < n; i++) {
    const [xi, yi, ri] = bombs[i];
    for (let j = 0; j < n; j++) {
      const dx = xi - bombs[j][0];
      const dy = yi - bombs[j][1];
      if (i !== j && dx * dx + dy * dy <= ri * ri) reach[i].push(j);
    }
  }
  let best = 0;
  for (let start = 0; start < n && best < n; start++) {
    const seen = new Array(n).fill(false);
    seen[start] = true;
    const stack = [start]; // depth-first works just as well as a queue here
    let count = 1;
    while (stack.length > 0) {
      for (const j of reach[stack.pop()]) {
        if (!seen[j]) {
          seen[j] = true;
          count++;
          stack.push(j);
        }
      }
    }
    best = Math.max(best, count);
  }
  return best;
}
JavaScript: the same graph, searched depth-first with an explicit stack

JavaScript numbers are 64-bit floats that hold whole numbers exactly up to 2⁵³, so squared distances stay exact for any coordinates you are likely to meet here. Since only the count matters, the order of the search does not, which is why a stack is fine.

The overflow trap in C++ and other fixed-width languages

With coordinates in the tens of thousands, a single squared difference can pass the 32-bit limit of about 2.1 billion. A difference of 60,000 squared is already 3.6 billion. Widen to 64 bits before multiplying.

// Squared distances of large coordinates overflow 32-bit int, so widen first.
bool setsOff(int xi, int yi, int ri, int xj, int yj) {
    long long dx = xi - xj, dy = yi - yj, r = ri;
    return dx * dx + dy * dy <= r * r;
}
C++: the edge test with 64-bit arithmetic

The subtraction xi - xj itself still happens in int, which is safe as long as the coordinates are non-negative and fit in an int. If coordinates can be negative and near the limits, cast before subtracting too.

Cost of each approach

n bombs, E directed edges (at most n²)
ApproachTimeExtra space
Repeated sweeps from each startO(n⁴) worst caseO(n)
Build edges, then BFS or DFS from each startO(n² + n(n + E)), so O(n³) worst caseO(n + E), up to O(n²)
Skip the edge list, test distances inside the searchO(n³)O(n)
n bombs, E directed edges (at most n²). Scroll sideways on a small screen.

The last row is a fair trade if memory is tight: instead of storing edges, the search tests every bomb against the one it just popped. It does the same O(n²) work per start without the adjacency list. Packing the visited sets into bitsets can cut the constant factor, but for this problem the cubic search is the expected answer. One idea you may hear is to collapse groups of bombs that all set each other off into a single node first. It can help on some inputs, but it does not change the worst case, so mention it only as an aside.

Edge cases to test

  • One bomb: the answer is 1.
  • No bomb in range of any other: the answer is 1, not 0.
  • Two bombs at the same point: distance 0, so each sets off the other.
  • A bomb exactly on the edge of another's circle: it counts. The squared comparison uses <=.
  • A large bomb next to a small one: the answer depends on which you light, which is the direction check.
  • Large coordinates where the squared distance passes 2³¹: fine in Python and JavaScript, needs 64-bit in C++ or Java.

Mistakes that cost points

  • Using union-find or undirected edges. Groups merge both ways, so a small bomb inherits the big bomb's reach and the answer comes out too high.
  • Comparing with the target bomb's radius instead of the source bomb's radius.
  • Taking square roots and comparing floats, which can miss an exact touch.
  • Reusing one visited array across different starting bombs, so later searches stop early.
  • Forgetting to count the starting bomb itself, which gives 0 for a single bomb.

Follow-up questions

  • Return which bomb to light, not just the count: keep the index whenever the best count improves.
  • You may light two bombs. The union of two reachable sets matters now, so compute every start's reachable set as a bitmask and test pairs: O(n²) pairs, each an OR of two masks.
  • Bombs are added one at a time. New edges can only add reach, so you can search again from the new bomb and from bombs that reach it. Talking through what changes is usually enough.
  • Blasts are squares instead of circles. Only the edge test changes: compare the larger of the x and y differences with the radius.

How to explain it out loud

Fictional example

Turning circles into a graph
Candidate
Each bomb is a node. I draw an arrow from A to B if B's center is within A's radius. The arrows are one-way because radii differ.
Interviewer
Why not group them with union-find?
Candidate
Because a big bomb can reach a small one that can't reach back. Union-find would give the small bomb the big one's reach.
Candidate
So I build the arrows once, compare squared distances to keep it in integers, then run a BFS from every bomb and take the biggest count. That's cubic in the worst case.
Candidate
If some start already reaches everything, I can stop early.

Clone Graph is the cleanest practice for walking an explicit graph with a visited map, and Number of Islands runs a similar search on a grid, where neighbors really are symmetric. From the same set as this page, Car Pooling is a sweep over sorted events, My Calendar I is an overlap check you answer one request at a time, and Design Twitter merges sorted lists with a heap.

Working through it with Natively

Geometry problems are easier to reason about once the picture is in front of you, and the leap from circles to arrows is the part to rehearse. While you practice on a Mac or Windows PC, Natively can read the bomb list from a screenshot, suggest the directed graph and the squared-distance test, and transcribe your mock explanation. Afterward you can check whether you raised the one-way edges and the overflow risk on your own. See how AI can help with coding interviews for the wider picture.

Questions people ask

How do you solve Detonate the Maximum Bombs?

Build a directed graph with an edge from bomb i to bomb j when j's center is within i's radius, comparing squared distances. Run a BFS or DFS from every bomb, count the bombs reached, and return the largest count.

Why doesn't union-find work for Detonate the Maximum Bombs?

Reach is one-way. A large bomb can set off a small one that cannot set it off back, but union-find merges both into one group and overstates what the small bomb reaches.

What is the time complexity of Detonate the Maximum Bombs?

Building the edges is O(n²) and a search from each of n bombs costs O(n + E), so the total is O(n³) in the worst case, with up to O(n²) space for the edges.

Does a bomb exactly on the edge of the blast radius explode?

Yes in the usual version: the test is distance at most the radius. Compare dx² + dy² <= r² with integers so an exact touch is never lost to rounding.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP