Find Center of Star Graph

There is an undirected star graph with n nodes labeled 1 to n. A star graph has one center node and exactly n - 1 edges, each joining the center to one of the other nodes. Given the 2D array edges, where edges[i] = [u, v] is an edge between u and v, return the center of the star.

30:00

Find Center of Star Graph
easy
Free written solution
Topics
Companies

There is an undirected star graph with n nodes labeled 1 to n. A star graph has one center node and exactly n - 1 edges, each joining the center to one of the other nodes. Given the 2D array edges, where edges[i] = [u, v] is an edge between u and v, return the center of the star.

Example 1:
Input: {"edges":[[1,2],[2,3],[4,2]]}
Output: 2
Constraints:
  • 3≤n≤1053 \leq n \leq 10^5

  • edges.length==n−1\text{edges.length} == n - 1

  • edges[i].length==2\text{edges}[i].\text{length} == 2

  • 1≤ui,vi≤n1 \leq u_i, v_i \leq n

  • ui≠viu_i \neq v_i

  • The given edges represent a valid star graph.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"edges":[[1,2],[2,3],[4,2]]}

A star with 4 nodes has one hub touching all 3 edges. The hub must appear in every edge, so two edges are enough to find it.

edges[0]

??ab

edges[1]

??cd
?
Variables
VariableValue
n4
DepthFunction Call
Stack empty
0/4