Graph Algorithms
![Question 41, GATE 2016: An undirected simple graph with n vertices and m edges uses adjacency lists. Entries [v] in u’s list and [u] in v’s list are twins. With unrestricted auxiliary memory, find the best time to set all twin pointers. A Θ(n²); B Θ(n+m); C Θ(m²); D Θ(n⁴).](../../assets/questions/CS-2016-S2-Q51-1.webp)
Answer & solution
Official answer: B
Number vertices 0..n−1. Scan the adjacency lists and record each entry’s pointer together with the ordered endpoint pair(min(u, v), max(u, v)). Two stable counting-sort passes on the endpoint labels sort all 2m records in O(n+m) time. Consecutive equal pairs are twins, so link their pointers in O(m). Scanning the n list heads and writing the 2m pointers gives the matching linear input/output bound in the adjacency-list model. Thus Θ(n+m), B; the algorithm uses allowed auxiliary memory without initializing an n² matrix.
Give each adjacency entry a record (min endpoint,max endpoint,address). Integer vertex labels permit stable counting sorts instead of comparison sorting’s extra logarithm. Simplicity ensures exactly two records per undirected edge, so matching neighbors after sorting is unambiguous. A dense n-by-n matrix is unnecessary and initializing it would lose the linear bound for sparse graphs.