1791 - Find Center of Star Graph
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] = [u_i, v_i]
indicates that there is an edge between the nodes u_i
and v_i
. Return the center of the given star graph.
Example:
Input: edges = [[1,2],[2,3],[4,2]]
Output: 2
n
) and edges (edges
)?
n
nodes and n-1
edges. Constraints: 3 <= n <= 10^5
.n
.To find the center of the star graph, observe that the center node will appear in every edge. Hence, it must be connected to n-1
other nodes. Given that the star graph always has exactly n-1
edges, the center node will show up most frequently in the edges
list.
We can solve this in a very straightforward manner:
Here is the solution to find the center of the star graph:
def findCenter(edges):
# Grabbing the nodes from the first two edges
u1, v1 = edges[0]
u2, v2 = edges[1]
# The center will be the common node between these two edges
if u1 == u2 or u1 == v2:
return u1
else:
return v1
# Example Test Case
edges = [[1,2], [2,3], [4,2]]
print(findCenter(edges)) # Output: 2
u1, v1
and u2, v2
.This approach ensures efficient and clear identification of the center node in the star graph.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?