Remove Max Number of Edges to Keep Graph Fully Traversable, explained

To remove the most edges while keeping the graph fully traversable for both Alice and Bob, keep two union-find structures and add edges greedily: shared edges first, into both structures, then Alice-only edges into hers and Bob-only edges into his. Count every edge that merges two components as kept. If either structure ends with more than one component, return -1; otherwise return total edges minus kept, in O(m · α(n)) time.

By Published 8 min read

The setup, in our words

There are n nodes labeled 1 to n and a list of undirected edges. Each edge has a type. Type 1 can be used only by Alice, type 2 only by Bob, and type 3 by both of them. The graph counts as fully traversable when Alice, using only the edges she may use, can get from any node to any other, and the same holds for Bob with his edges. Return the largest number of edges you can delete while the graph stays fully traversable. If it is not fully traversable even with every edge in place, return -1.

Graphs designed for this page (type, u, v)
nEdgesAnswerWhat gets removed
4(3,1,2) (3,2,3) (3,1,3) (1,3,4) (2,3,4) (1,2,4)2The shared 1-3, which closes a cycle, and Alice's 2-4, which she no longer needs
3(3,1,2) (1,2,3) (2,2,3) (1,1,3) (2,1,3)2One private edge each for Alice and Bob
3(3,1,2) (3,1,2) (3,2,3)1The duplicate shared edge
3(1,1,2) (1,2,3) (2,1,2)-1Bob can never reach node 3
1none0One node is already traversable
Graphs designed for this page (type, u, v). Scroll sideways on a small screen.

Ask early whether duplicate edges or edges with the same endpoints but different types can appear. They usually can, and the algorithm below handles them without special cases, but the question shows you are thinking about the input rather than the happy path.

What this question checks

Most candidates know that a connected graph on n nodes needs n - 1 edges in a spanning tree. The question is whether you can extend that to two overlapping graphs and justify a greedy order. Interviewers listen for the argument that shared edges are worth more, and for clean handling of the -1 case. It is also a good test of writing a small reusable union-find instead of copying the same code twice.

Slow approach: test subsets of edges

Try keeping 0 edges, then every set of 1 edge, then every set of 2, and so on. For each candidate set, check with a graph search that Alice's edges and Bob's edges each connect all n nodes. The first size that works is the minimum you must keep, and the answer is the total minus that size. If no subset works, not even the full list, return -1.

from itertools import combinations

def max_removable_slow(n, edges):
    def spans(chosen, kinds):
        adj = {v: [] for v in range(1, n + 1)}
        for kind, u, v in chosen:
            if kind in kinds:
                adj[u].append(v)
                adj[v].append(u)
        seen, stack = {1}, [1]
        while stack:
            for nxt in adj[stack.pop()]:
                if nxt not in seen:
                    seen.add(nxt)
                    stack.append(nxt)
        return len(seen) == n

    for keep in range(len(edges) + 1):
        for chosen in combinations(edges, keep):
            if spans(chosen, (1, 3)) and spans(chosen, (2, 3)):
                return len(edges) - keep
    return -1
Exhaustive search over kept subsets, exponential in the number of edges.

This is a reliable checker for graphs with ten or so edges and useless beyond that. Its value in an interview is that it states the goal precisely: find the smallest set of kept edges that spans both views of the graph.

Main approach: two disjoint sets, shared edges first

Each person needs a spanning tree of n - 1 edges over their own view. Shared edges can sit in both trees at once. If t shared edges end up in both trees, the kept total is t + 2 × (n - 1 - t) = 2(n - 1) - t. So the fewer edges you keep, the more shared edges you must have put to use, and the goal becomes: use as many shared edges as possible.

That gives the order. First, run through the type 3 edges and union them in both structures; an edge that merges two components is kept, one that closes a cycle is removable. Since both structures receive exactly the same unions at this stage, they stay identical, and any spanning forest of the shared edges uses the same maximum number of them. Then run the type 1 edges through Alice's structure only and the type 2 edges through Bob's, keeping each edge that merges something. Finally, if either structure still has more than one component, return -1.

class Forest:
    def __init__(self, n):
        self.up = list(range(n + 1))
        self.parts = n

    def find(self, x):
        while self.up[x] != x:
            self.up[x] = self.up[self.up[x]]
            x = self.up[x]
        return x

    def join(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        self.up[ra] = rb
        self.parts -= 1
        return True


def max_removable(n, edges):
    alice, bob = Forest(n), Forest(n)
    kept = 0
    for kind, u, v in edges:
        if kind == 3 and alice.join(u, v):
            bob.join(u, v)
            kept += 1
    for kind, u, v in edges:
        if kind == 1 and alice.join(u, v):
            kept += 1
        elif kind == 2 and bob.join(u, v):
            kept += 1
    if alice.parts > 1 or bob.parts > 1:
        return -1
    return len(edges) - kept
Python: a small class with a component counter, used twice.
function makeForest(n) {
  const up = Array.from({ length: n + 1 }, (_, i) => i);
  const weight = new Array(n + 1).fill(1);
  let parts = n;
  const find = (x) => {
    while (up[x] !== x) {
      up[x] = up[up[x]];
      x = up[x];
    }
    return x;
  };
  const join = (a, b) => {
    let ra = find(a);
    let rb = find(b);
    if (ra === rb) return false;
    if (weight[ra] < weight[rb]) [ra, rb] = [rb, ra];
    up[rb] = ra;
    weight[ra] += weight[rb];
    parts -= 1;
    return true;
  };
  return { join, parts: () => parts };
}

function maxRemovable(n, edges) {
  const alice = makeForest(n);
  const bob = makeForest(n);
  let kept = 0;
  for (const [kind, u, v] of edges) {
    if (kind === 3 && alice.join(u, v)) {
      bob.join(u, v);
      kept += 1;
    }
  }
  for (const [kind, u, v] of edges) {
    if (kind === 1 && alice.join(u, v)) kept += 1;
    else if (kind === 2 && bob.join(u, v)) kept += 1;
  }
  if (alice.parts() > 1 || bob.parts() > 1) return -1;
  return edges.length - kept;
}
JavaScript: a factory function instead of a class, with union by size.

The shared pass only checks Alice's structure before joining Bob's. That shortcut is safe because, during that pass, the two structures receive identical unions and so always agree. If you find it too clever for the room, call join on both and keep the edge when either returns true; the result is the same.

Trace on the first example

n = 4. Shared pass: 1-2 merges (kept 1), 2-3 merges (kept 2), 1-3 closes a cycle and is removable. Private pass: Alice's 3-4 merges (kept 3), Bob's 3-4 merges (kept 4), Alice's 2-4 finds 2 and 4 already connected and is removable. Both structures have one component, so the answer is 6 - 4 = 2.

Complexity

n nodes, m edges
ApproachTimeExtra spaceUse
Every subset of kept edgesO(2^m · (n + m))O(n + m)Checking tiny cases
Two union-find structures, shared firstO(m · α(n))O(n)The expected answer
n nodes, m edges. Scroll sideways on a small screen.

Cases to check

  • n = 1: already traversable, so every edge (if any) is removable.
  • No shared edges at all: the answer is m - 2(n - 1) when both people can connect, else -1.
  • Only shared edges: the answer is m - (n - 1) when they connect the graph.
  • Duplicate edges of the same type: the second copy is always removable.
  • One person connected and the other not: return -1, even if the connected side has spare edges.

Pitfalls

  • Processing edges in input order. A private edge taken early can block a shared edge later, and you keep one edge too many.
  • Counting a shared edge as kept twice because it joined both structures.
  • Sizing the parent arrays for n instead of n + 1 when nodes are labeled from 1.
  • Checking connectivity only for Alice, or only once at the end of the shared pass.
  • Returning the number of kept edges instead of the number removed.

How to pitch it

Fictional example

The argument in three moves
Candidate
Each person needs a spanning tree, n minus 1 edges each. A shared edge can serve both trees, so if t shared edges are used, I keep 2(n minus 1) minus t edges in total.
Candidate
To keep the fewest, I maximize t, which means adding every useful shared edge before any private one. Union-find tells me whether an edge merges anything or just closes a cycle.
Candidate
Then private edges go into each person's structure. If either one is still split, the answer is minus 1; otherwise it is total edges minus kept.

Back to the start of the set

Number of Good Paths is the other union-find problem here that depends on processing edges in the right order. For a change of pattern, Divide Chocolate opens this set with binary search on the answer. Graph and disjoint-set fundamentals are on the data structure interview questions page.

Practicing this with Natively

When you practice graph problems, Natively can read the statement from a screenshot and offer a plan and code, which helps most when you compare it with your own greedy argument afterward. Each mock session is transcribed on your computer, so you can review whether you explained the 2(n - 1) - t count. More about an AI interview assistant for Mac and Windows.

Questions people ask

How do you solve Remove Max Number of Edges to Keep Graph Fully Traversable?

Keep one union-find for Alice and one for Bob. Add shared edges to both first, then Alice-only and Bob-only edges to their own structures, counting each edge that merges two components. If either ends with more than one component return -1, else return total edges minus kept.

Why process shared edges first?

Each person needs n - 1 edges, and a shared edge counts for both. If t shared edges are used, the kept total is 2(n - 1) - t, so using as many shared edges as possible keeps the fewest edges.

What is the time complexity?

O(m · α(n)) for m edges and n nodes with path compression and union by size, which is nearly linear. Extra space is O(n) for the two structures.

When is the answer -1?

When Alice or Bob cannot reach every node even with all edges kept. After all unions, one of the two structures still has more than one component.

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