Last Updated: 26 Jan, 2022

Find Center of Star Graph

Easy
Asked in companies
MicrosoftCIS - Cyber Infrastructure

Problem statement

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.
Input Format :
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.
Constraints :
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

Approaches

01 Approach

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 :

  1. Declare a HashMap, ‘mp’ to store the count of edges connecting to a node.
  2. For every edge, we increment the count of its node in ‘mp’.
  3. for ‘e’ in ‘EDGES’:
    • mp[e[0]]++, mp[e[1]]++
  4. Go through ‘mp’ and find the centre of the graph.
  5. for ‘pair’ in ‘mp’:
    • if pair.second == m:
      • return pair.first

02 Approach

We can notice that the centre node has to appear in every edge. This means the node that appears in both EDGES[0] and EDGES[1] will be the center node. This is much better than direct implementation.

 

The steps are as follows :

  1. If the first node of ‘EDGES[0]’ occurs in ‘EDGES[1]’ as well, it's the centre one.
  2. Otherwise, the second node of ‘EDGES[0]’ will be the center node for sure.