#1791

Find Center of Star Graph

Easy
Graph TheoryHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(n)
O(1)
💡

Intuition

Time O(1)Space O(1)

In a star graph, the center node is directly connected to all other nodes. Thus, we can simply check the first two edges to determine the center, as it must be one of the nodes in those edges.

⚙️

Algorithm

2 steps
  1. 1Step 1: Return the first node of the first edge if it is also present in the second edge.
  2. 2Step 2: If not, return the second node of the first edge.
solution.py4 lines
1# Full working Python code
2
3def findCenter(edges):
4    return edges[0][0] if edges[0][0] in edges[1] else edges[0][1]

Complexity note: The time complexity is O(1) because we only check the first two edges. The space complexity is O(1) since we do not use any additional data structures.

  • 1The center node is the only one connected to all other nodes.
  • 2Checking the first two edges is sufficient to find the center.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.