Chat app~20 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-261dfs
You work on the relay network of a chat app. Messages pass between n relay servers, numbered 0 to n - 1, over two-way links.
The network is valid only when it is a tree: every server can reach every other server, and by exactly one path. A loop makes a message circulate, and a cut-off server never receives anything. A deploy script must check a proposed link map and reject it before it goes live.
Write is_tree(n, links).
n is the number of servers.links[i] = [a, b] is a two-way link between servers a and b, with a ≠ b.true when the links form a tree: all n servers are connected, and there is no loop.Input: n = 5, links = [[0, 1], [0, 2], [0, 3], [1, 4]]
Output: trueFive servers and four links, and every server is reached from server 0.
| Step | Take | Stack after | Servers reached |
|---|---|---|---|
| start | 0 | 1 | |
| 1 | 0 | 1, 2, 3 | 4 |
| 2 | 3 | 1, 2 | 4 |
| 3 | 2 | 1 | 4 |
| 4 | 1 | 4 | 5 |
| 5 | 4 | 5 |
All 5 servers were reached, so the answer is true.
Input: n = 5, links = [[0, 1], [1, 2], [2, 3], [1, 3]]
Output: falseServers 1, 2 and 3 form a loop, and server 4 has no link. There are four links for five servers, so the count looks right, but the shape is not.
Input: n = 1, links = []
Output: trueOne server is a tree with zero links.
1 ≤ n ≤ 100,0000 ≤ len(links) ≤ 100,000, and every row is [a, b] with 0 ≤ a, b < n and a ≠ bThere can be 100,000 servers and 100,000 links. Merging groups by relabelling every server on each link costs n × m, about 10 billion steps. The answer must touch each server and link a few times: n + m.