Problem of the day
You have been given an undirected star graph in the form of Adjacency List 'EDGES', consisting of ‘N’ nodes labelled from 1 to ‘N’. A star graph is a graph where there is one centre node and exactly ‘N’ - 1 edges that connect the centre node to every other node.
You are given a matrix ‘EDGES’ storing the information about the edges, where each row, ‘EDGES[i]’ contains two integers ‘U’ and ‘V’, which implies that there is an undirected edge between ‘U’ and ‘V’.
For Example :For the given graph:
Node 1 is connected to all other nodes. Hence node 1 is the centre of this star graph.
The first line contains an integer 'T' which denotes the number of test cases.
The first line of each test case contains ‘M’, no of edges.
The following ‘M’ lines contain two integers ‘U’ and ‘V’ denoting there is an undirected edge between node ‘U’ and node ‘V’.
Output Format :
For each test case, return the centre of the given star graph.
The first and only line of output of each test case prints the centre of a given star graph.
Note :
You don't need to print anything, it has already been taken care of. Just implement the given function.
1 ≤ T ≤ 10
3 ≤ M ≤ 10^4
M is always equal to N - 1
EDGES.length = M
1 ≤ U, V ≤ N
Time limit: 1 sec
2
3
2 1
3 1
1 4
3
1 2
2 3
4 2
1
2
In test case 1, the graph is shown below.
Node 1 is connected to all other nodes. Hence node 1 is the centre of this star graph.
In test case 2, the graph is shown below.
Node 2 is connected to all other nodes. Hence node 2 is the centre of this star graph.
2
3
2 3
3 1
3 4
4
1 2
2 3
4 2
2 5
3
2
In test case 1, the graph is shown below.
Node 3 is connected to all other nodes. Hence node 3 is the centre of this star graph.
In test case 2, the graph is shown below.
Node 2 is connected to all other nodes. Hence node 2 is the centre of this star graph.
The centre is the only node that has more than one edge. The centre is also connected to all other nodes.
Looking at the problem, we can directly see that the node having ‘M’ number of edges connecting it, where ‘M’ is the number of edges, will be the centre node.
The steps are as follows :
O( N ), where ‘N’ is the total number of nodes in the given graph.
We traverse all edges in ~O ( M ) time. At last, we also need to traverse the HashMap, we check for every node in the worst case. But ‘N’ is greater than ‘M’.
Hence the time complexity is O( N ).
O( N ), where ‘N’ is the total number of nodes in the given graph.
We are using a HashMap to store nodes and their connecting edges.
Hence the space complexity is O( N ).