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
Find Center of Star Graph INPUT Star Graph Structure 2 1 3 4 edges array: [1,2] [2,3] [4,2] n = 4 nodes 3 edges total ALGORITHM STEPS 1 Get first two edges edges[0] = [1,2] edges[1] = [2,3] 2 Extract all nodes From edge 1: 1, 2 From edge 2: 2, 3 3 Find common node Center appears in BOTH edges (by definition) 4 Check condition If edges[0][0] in edge[1] --> return edges[0][0] else return edges[0][1] 1 in [2,3]? NO 2 in [2,3]? YES OK FINAL RESULT Center Identified 2 1 3 4 Output: 2 Node 2 is the center of the star graph Time: O(1) Key Insight: In a star graph, the center node is connected to ALL other nodes. Therefore, it must appear in EVERY edge. By checking just the first two edges, we can find the common node in O(1) time. No need to count degrees or traverse the entire edge list - two edges are sufficient! TutorialsPoint - Find Center of Star Graph | Two-Edge Check Approach
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