Print nodes having maximum and minimum degrees
Given an undirected graph having N nodes, the task is to print the nodes having minimum and maximum degree.
Input: 1-----2 | | 3-----4 Output: Nodes with maximum degree : 1 2 3 4 Nodes with minimum degree : 1 2 3 4 Every node has a degree of 2. Input: 1 / \ 2 3 / 4 Output: Nodes with maximum degree : 1 2 Nodes with minimum degree : 3 4
Approach: For an undirected graph, the degree of a node is the number of edges incident to it, so the degree of each node can be calculated by counting its frequency in the list of edges. Hence the approach is to use a map to calculate the frequency of every vertex from the edge list and use the map to find the nodes having maximum and minimum degrees.
Below is the implementation of the above approach:
Nodes with maximum degree : 1 2 3 4 Nodes with minimum degree : 1 2 3 4
Time Complexity: O(M*logN + N).
Auxiliary Space: O(N).