Took me a minute to even parse what they were asking.
First, validate the basic edge count conditions for each topology: Bus requires M = N-1, Ring requires M = N, and Star requires M = N-1. Then, compute the degree of each node and check the degree distribution: Bus has exactly two nodes of degree 1 and all others degree 2; Ring has all nodes degree 2; Star has one node of degree N-1 and all others degree 1. Finally, for Bus and Ring, verify connectivity to rule out disjoint cycles or multiple components.
Pro tip: Always handle edge cases like N=1, N=2, and self-loops or duplicate edges explicitly, and mention that the solution runs in O(N+M) time, which is optimal for this problem.
Verify if M equals N-1 (possible Bus or Star) or M equals N (possible Ring). If neither, return -1 immediately.
Traverse all edges and count the degree of each node. This will help identify the degree distribution pattern.
For Star: exactly one node has degree N-1 and all others degree 1. For Bus: exactly two nodes have degree 1 and all others degree 2. For Ring: all nodes have degree 2.
Use BFS/DFS or Union-Find to ensure the graph is connected. For Bus, also ensure no cycles (which is implied by M=N-1 and connectivity). For Ring, ensure it's a single cycle.
Check for N=1 (single node: could be considered Bus or Ring? clarify with interviewer), N=2 (two nodes with one edge: Bus), and ensure no self-loops or multiple edges. Return the appropriate topology code.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.