Find Center of Star Graph — LeetCode 1791 Python Solution

EasyGraph
Problem
#1791
Reading time
2 min

The 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.

Example

Input
edges = [[1,2],[2,3],[4,2]]
Output
2
Explanation
As shown in the figure above, node 2 is connected to every other node, so 2 is the center.

Python solution

Python
class Solution:
    def findCenter(self, edges: List[List[int]]) -> int:
        return edges[0][0] if edges[0][0] in edges[1] else edges[0][1]

Complexity

MeasureComplexity
TimeO(1)
SpaceO(1) auxiliary

Pattern: Depth-First Search

Follow one path to its end before trying the next — the default way to explore a graph. LeetCode 1791. Find Center of Star Graph is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Graph.

The depth-first search guide has the Python template for the pattern and the 366 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1791. Find Center of Star Graph?
LeetCode 1791. Find Center of Star Graph is rated Easy on LeetCode.
What is the time complexity of LeetCode 1791. Find Center of Star Graph?
The Python solution on this page runs in O(1).
What is the space complexity of LeetCode 1791. Find Center of Star Graph?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1791. Find Center of Star Graph cover?
LeetCode 1791. Find Center of Star Graph is tagged Graph on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview