Problem
There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node.
You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.
Examples
Example 1:
graph TB
1
1 --- 2
2 --- 3
2 --- 4
| |
Example 2:
graph TB
2
3
2 --- 1
3 --- 1
1 --- 4
1 --- 5
| |
Solution
Method 1 - Count number of edges per node
We have total n edges in star graph, and n+1 nodes. For all nodes, the center node will have n edges connected to it. So, we sill just count the number of edges per node, and return the node which has n edges connected to it.
Code
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(n)
Method 2 - Just Look at 2 edges
We can notice that the center node has to appear in every edge. This mean the node that appears in both edge[0] and edge[1] will be the center node. So, we just need 2 edges to check that, and find out the common node OR center node.
Here is the video explanation:
Code
| |
Complexity
- ⏰ Time complexity:
O(1) - 🧺 Space complexity:
O(1)