Find Center of Star Graph - Problem

Imagine a star-shaped network where one central hub connects to every other node, but no other connections exist between the outer nodes. This is called a star graph!

You're given an undirected star graph with n nodes labeled from 1 to n. In a star graph, there's exactly one center node that connects to all other n-1 nodes, forming a perfect star pattern โญ.

Your task is to identify which node is the center of this star graph. You'll receive a 2D array edges where each edges[i] = [ui, vi] represents an undirected edge between nodes ui and vi.

Goal: Return the label of the center node.

Key insight: Since it's guaranteed to be a star graph, the center node will appear in every single edge, while all other nodes appear in exactly one edge!

Input & Output

example_1.py โ€” Simple Star
$ Input: edges = [[1,2],[2,3],[4,2]]
โ€บ Output: 2
๐Ÿ’ก Note: Node 2 is connected to nodes 1, 3, and 4, forming a perfect star with 2 at the center. All edges contain node 2, making it the center.
example_2.py โ€” Minimum Star
$ Input: edges = [[1,2],[5,1],[1,3],[1,4]]
โ€บ Output: 1
๐Ÿ’ก Note: Node 1 connects to all other nodes (2, 3, 4, 5). This creates a star pattern with 1 as the central hub.
example_3.py โ€” Large Center ID
$ Input: edges = [[100,1],[100,2],[100,3]]
โ€บ Output: 100
๐Ÿ’ก Note: Even with a large node ID, node 100 is clearly the center as it appears in every edge, connecting to nodes 1, 2, and 3.

Constraints

  • 3 โ‰ค n โ‰ค 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 1 โ‰ค ui, vi โ‰ค n
  • ui โ‰  vi
  • The given input is guaranteed to be a valid star graph

Visualization

Tap to expand
Star Graph: Finding the Center21345Edge [1,2] โœ“Edge [2,3] โœ“Edge [4,2] โœ“Edge [5,2] โœ“Node 2 appears in ALL edges โ†’ CENTER!
Understanding the Visualization
1
Recognize the Pattern
In a star graph, exactly one node connects to all others - this is the center
2
Key Insight
The center node must appear in EVERY single edge of the graph
3
Smart Check
Instead of counting all edges, just check which node appears in both the first and second edge
Key Takeaway
๐ŸŽฏ Key Insight: The center of a star graph appears in every edge, so we can identify it by checking just the first two edges for the common node!
Asked in
Google 23 Amazon 18 Meta 15 Microsoft 12
67.5K Views
Medium Frequency
~8 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen