1791. Find Center of Star Graph
EasyView on LeetCode
Time: O(1)
Space: O(1)
Advertisement
Intuition
The center node is connected to all other nodes. Find the node that appears in all edges.
Algorithm
- 1Center must appear in both edges[0] and edges[1]. Find common node.
Common Pitfalls
- •With n>=3 nodes and n-1 edges in a star, center appears in every edge. Just check first two edges.
1791.cs
C#
// Approach: Center node appears in both first two edges; compare endpoints directly.
// Time: O(1) Space: O(1)
public class Solution
{
public int FindCenter(int[][] edges)
{
return (edges[0][0] == edges[1][0] || edges[0][0] == edges[1][1])
? edges[0][0]
: edges[0][1];
}
}Advertisement
Was this solution helpful?