Find Center of Star Graph - 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.

Input & Output

Example 1 — Basic Star Graph
$ Input: edges = [[1,2],[2,3],[4,2]]
Output: 2
💡 Note: Node 2 is connected to all other nodes (1, 3, and 4), making it the center of the star graph
Example 2 — Different Center
$ Input: edges = [[1,2],[5,1],[1,3],[1,4]]
Output: 1
💡 Note: Node 1 is connected to all other nodes (2, 3, 4, and 5), making it the center
Example 3 — Minimum Star Graph
$ Input: edges = [[1,2]]
Output: 1
💡 Note: With only one edge, either node can be considered center, but node 1 appears first

Constraints

  • 3 ≤ n ≤ 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 1 ≤ ui, vi ≤ n
  • ui ≠ vi
  • The given edges represent a valid star graph

Visualization

Tap to expand
Star Graph: Find the Center NodeInput: [[1,2],[2,3],[4,2]]2134Center: Node 2 (connected to all others)
Understanding the Visualization
1
Input
2D array of edges representing connections
2
Process
Find node that appears in most connections
3
Output
Return the center node number
Key Takeaway
🎯 Key Insight: The center node appears in every edge, so checking the first two edges is enough
Asked in
Facebook 25 Google 20 Amazon 15
28.5K Views
Medium Frequency
~8 min Avg. Time
892 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