Find Center of Star Graph — Solution in Python, Java & C++
Find Center of Star Graph solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on graph.
Find Center of Star Graph is an easy coding problem on graph.
- Difficulty: Easy
- Topics: Graph
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
A star graph of n nodes has one center connected to every other node by exactly one edge. Given its edge list, return the center node.
Example 1
Input: edges = [[1,2],[2,3],[4,2]]
Output: 2
Example 2
Input: edges = [[1,2],[5,1],[1,3],[1,4]]
Output: 1
Constraints
3 <= n <= 20edges.length == n - 1The given edges form a valid star graph.
Hints for Find Center of Star Graph
Hint 1
The center appears in EVERY edge.
Hint 2
Compare just the first two edges — the common endpoint is the center.
How to solve Find Center of Star Graph
In a star every edge touches the centre, and no edge joins two leaves. So the centre is the one node the edges have in common — and you only need two edges to find it. Whichever endpoint of the first edge also appears in the second must be the centre, because a leaf appears in exactly one edge.
Approach
- Take the two endpoints
aandbofedges[0]. - Check whether
aappears inedges[1]. - If it does,
ais the centre; otherwise it isb. - No traversal, no counting, no scan of the rest of the list.
Why it works
A star with n nodes has n - 1 edges, each connecting the centre to a distinct leaf. Every leaf therefore has degree 1 and sits in exactly one edge, while the centre sits in all of them. Since n >= 3 there are at least two edges, and the only node they can share is the centre — two distinct leaves never share an edge.
Complexity
- Time —
O(1) - Space —
O(1)
Pitfalls
- Counting degrees over the whole edge list works but is
O(n)for no reason — two edges settle it. - The centre may appear as either endpoint, so check
aagainst both entries of the second edge. n >= 3guarantees a second edge exists; with only one edge the centre would be genuinely ambiguous.
Reference solution
Python
from typing import List
def findCenter(edges: List[List[int]]) -> int:
a, b = edges[0]
return a if a in edges[1] else bJava
public static int findCenter(int[][] edges) {
int a = edges[0][0];
int b = edges[0][1];
return (a == edges[1][0] || a == edges[1][1]) ? a : b;
}C++
int findCenter(vector<vector<int>>& edges) {
int a = edges[0][0];
int b = edges[0][1];
return (a == edges[1][0] || a == edges[1][1]) ? a : b;
}JavaScript
var findCenter = function(edges) {
const a = edges[0][0], b = edges[0][1];
return (a === edges[1][0] || a === edges[1][1]) ? a : b;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 107 graph problems · the whole catalogue
Learn the technique: Graph Data Structure