Graph Valid Tree
Check that the links join every node into one piece with no loop
DSA, Medium, Graphs
Which structure or algorithm, and what does it cost.
There are n rooms, numbered 0 to n - 1. Each link [a, b] is a corridor that joins room a and room b in both directions. The rooms form a tree if every room can reach every other room and there is exactly one route between any two rooms, so there is no circle. Write is_tree(n, links). It returns true if the rooms form a tree and false if not. Two links between the same two rooms make a circle.
Examples
Constraints
- 1 <=
n<= 60,000. - 0 <= number of links <= 100,000.
- Every room number is between 0 and n - 1, and a != b in every link. A link may appear more than once.
Your answer must contain
- Why n - 1 links plus one joined piece is enough; the method; code; time and memory cost; a hand trace of example 1; the answer for one room.
Target Aim for O(n + m) time and memory, where m is the number of links.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Picture a tree of rooms. It has no circle and no room is cut off. What does that say about how many links it can have?
Hint 2 the approach
If there are exactly n - 1 links, which single check is left?
Hint 3 the key step
If the links do not number n - 1, answer false. Otherwise search from room 0 and count the rooms you reach. True only if you reach all n.
Walkthrough
Full walkthrough brute force to best
Brute force
First check that every room can be reached from room 0, with one search. Then, for each link in turn, take it out and search again. In a tree every link is the only route between its two rooms, so every removal must cut the rooms in two. That is m + 1 searches of O(n + m) each, so this costs O(m * (n + m)) time.
Best method
A joined set of n rooms needs at least n - 1 links, and a tree uses exactly that many. So if the number of links is not n - 1, answer false at once. If it is n - 1, then the rooms form a tree exactly when they are all joined: with only n - 1 links, every link is needed to join something, so there is none left over to make a circle. Build the neighbour list of each room. Search from room 0, marking the rooms you reach. If you reach all n rooms, answer true. Otherwise some room is cut off, so answer false.
Hand trace
Example 1: there are 5 links and n - 1 is 5, so the count fits. The neighbours are 0: [4], 4: [0, 2, 5], 2: [4, 3], 5: [4, 1], 3: [2] and 1: [5]. The search from room 0 visits 0, 4, 2, 5, 3 and 1, which is 6 rooms. That is all n rooms, so the answer is true.
Code
from collections import deque
def is_tree(n, links):
if len(links) != n - 1: # a tree of n rooms has exactly n - 1 links
return False
near = [[] for _ in range(n)]
for a, b in links:
near[a].append(b)
near[b].append(a)
seen = {0}
todo = deque([0])
while todo:
x = todo.popleft()
for y in near[x]:
if y not in seen:
seen.add(y)
todo.append(y)
return len(seen) == n # joined, and with n - 1 links there is no room for a circleTime and memory
O(n + m) time and O(n + m) memory, where m is the number of links. Counting the links is O(1), building the neighbour lists reads each link once, and the search marks each room once.
Common mistakes
- Checking only for a circle. Two separate pieces can have no circle, but they are not one tree.
- Checking only that every room is reached. A graph with extra links can join all the rooms and still have a circle.
- Treating a repeated link as harmless. Two links between the same two rooms make a circle. With n - 1 links, a repeat leaves too few links to join every room, so the search from room 0 misses a room.