Minimum Number of Vertices to Reach All Nodes, explained

Minimum Number of Vertices to Reach All Nodes gives you a directed graph with no cycles and asks for the smallest set of starting nodes from which every node can be reached. The answer is exactly the nodes with no incoming edges: nothing else can reach them, so they must be in the set, and in an acyclic graph every other node can be traced back to one of them. One pass over the edges finds them in O(V + E).

By Published 7 min read

The problem, restated

You get n nodes numbered 0 to n - 1 and a list of directed edges, with a promise that the graph has no cycles. Choose a set of starting nodes so that every node is either in the set or reachable from some node in it by following edges. Return the smallest such set. It turns out to be unique, so any order of the nodes is acceptable, and the code below returns them in increasing order.

0 -> 2    1 -> 2
2 -> 3    4 -> 3
4 -> 5    6 -> 5

answer: [0, 1, 4, 6]
Seven nodes and six edges, made up for this page.

Nodes 0, 1, 4 and 6 have no edges pointing into them. Starting from those four, node 2 is reached from 0 or 1, node 3 from 2 or 4, and node 5 from 4 or 6. No smaller set works, because each of the four can only be reached by starting at it.

What the interviewer is checking

The code is a few lines, so this question is really about the argument. Interviewers want you to show both halves of the proof: why the chosen nodes are necessary and why they are enough. They also like to hear you point out where the no-cycles promise is used, because the follow-up is almost always "what if the graph had cycles?"

Brute force: try sets from smallest to largest

Without the insight, you can test every set of starting nodes in order of size and return the first one whose reachable set covers everything. Checking a set is a graph search, O(V + E), but the number of sets is 2 to the power n, so this is only usable for very small graphs. It makes a good reference for testing the fast version.

from itertools import combinations

def smallest_start_set_brute(n, edges):
    out = [[] for _ in range(n)]
    for a, b in edges:
        out[a].append(b)

    def covers(starts):
        seen, stack = set(starts), list(starts)
        while stack:
            for nxt in out[stack.pop()]:
                if nxt not in seen:
                    seen.add(nxt)
                    stack.append(nxt)
        return len(seen) == n

    for size in range(1, n + 1):  # try small sets first
        for starts in combinations(range(n), size):
            if covers(starts):
                return list(starts)
Python: subset search, exponential, for testing.

The in-degree argument

Necessary: if a node has no incoming edge, no path from any other node ends at it, so the only way to cover it is to start there. Every in-degree-zero node must be in the answer.

Sufficient: take any node v with at least one incoming edge. Step backward along one of those edges to a parent, and keep stepping back while the current node has a parent. Because the graph has no cycles, you can never revisit a node, so after at most n steps you stop at a node with no incoming edge. Read forward, that backward walk is a path from an in-degree-zero node to v. So the in-degree-zero nodes reach everything, and the set is both necessary and sufficient, which also makes it unique.

def smallest_start_set(n, edges):
    has_incoming = [False] * n
    for _, b in edges:
        has_incoming[b] = True
    return [v for v in range(n) if not has_incoming[v]]
Python: mark every node that some edge points to, return the rest.
function smallestStartSet(n, edges) {
  const hasIncoming = new Array(n).fill(false);
  for (const [, to] of edges) hasIncoming[to] = true;
  const starts = [];
  for (let v = 0; v < n; v++) if (!hasIncoming[v]) starts.push(v);
  return starts;
}
JavaScript: the same single pass.

There is no need to build an adjacency list or run any search. A boolean per node is enough, though counting in-degrees instead of marking them works too and reads naturally if you go on to a topological sort.

Checking the example

The edges point into 2, 2, 3, 3, 5 and 5. Marking those leaves 0, 1, 4 and 6 unmarked, which is the answer. Take node 3 as a check of the backward walk: its parent 2 has parent 0, which has no parent, so 0 reaches 3.

Complexity

V nodes, E edges
ApproachTimeExtra space
Every set of start nodes, smallest firstO(2^V · (V + E))O(V + E)
Search from each node and drop any node reached by anotherO(V · (V + E))O(V + E)
Nodes with no incoming edgeO(V + E)O(V)
V nodes, E edges. Scroll sideways on a small screen.

Edge cases

  • No edges at all: every node is its own start, so the answer is all n nodes.
  • A single chain 0 to 1 to 2 and so on: only the first node is needed.
  • Several separate pieces: each piece contributes its own sources.
  • Repeated edges: marking twice is harmless.
  • A node that appears in no edge: it has no incoming edge, so it is in the answer.

Common mistakes

  • Returning nodes with no outgoing edges, which are the sinks, not the sources.
  • Running a search from every node to find which ones are reachable, which works but misses the simple argument.
  • Leaving out isolated nodes that never appear in the edge list.
  • Claiming the rule holds for graphs with cycles without checking; it does not.

Follow-up questions

  • The graph may contain cycles. A cycle with no edge coming in from outside has no in-degree-zero node, yet one of its nodes must be chosen. Collapse strongly connected components first, then take one node from each component that has no incoming edge.
  • Return how many nodes each start can reach. Run a search from each start. Adding up children's counts over a topological order does not work, because two children can reach the same node and it would be counted twice.
  • Edges arrive as a stream. Keep the boolean array and update it as edges come in; the current answer is always the unmarked nodes.
  • Find the nodes that every other node can reach. Reverse the roles: in an acyclic graph, look at nodes with no outgoing edges and check whether there is exactly one.

How to explain it

Fictional example

Proving the rule before writing it
Candidate
Any node with no incoming edge can't be reached from anywhere else, so it has to be in the set.
Candidate
For every other node, I can walk backward through parents. With no cycles, that walk has to end at a node with no incoming edge, and reading it forward gives a path to my node. So those nodes are enough.
Candidate
That means one pass marking edge targets, and the unmarked nodes are the answer. Linear in nodes plus edges.

Find Eventual Safe States also reasons about a directed graph's structure, peeling nodes by their out-degree. Bus Routes is a reachability search where the starting set matters, and Count Sub Islands applies a whole-component check on a grid. The coding problems hub lists every walkthrough.

Practicing proof-first problems with Natively

Short problems like this one are judged mostly on the explanation. When you practice on Mac or Windows, Natively can read the graph from a screenshot, and you can ask it to check your argument for why each node belongs in the set, or to suggest the one-pass code once you have made that argument yourself. The transcript of the mock is saved with notes, so you can check whether you gave both halves of the proof or only the rule. The AI interview assistant page has the details.

Questions people ask

How do you solve Minimum Number of Vertices to Reach All Nodes?

Return every node with no incoming edge. Mark each edge's target in one pass over the edges; the unmarked nodes are the answer.

Why are nodes with in-degree zero the answer?

Nothing else can reach them, so they must be chosen. In a graph with no cycles, every other node can be traced back through parents to one of them, so they are also enough.

What is the time complexity of Minimum Number of Vertices to Reach All Nodes?

O(V + E): one pass over the edges and one over the nodes.

What if the graph has cycles?

The rule no longer holds. Collapse strongly connected components and take one node from each component with no incoming edge.

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