1791. Find Center of Star Graph
EasyView on LeetCode
Time: O(1)
Space: O(1)
Problem Overview
The center node is connected to all other nodes.
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];
}
}Was this solution helpful?
Related Problems
- 126. Word Ladder II(Hard)
- 210. Course Schedule II(Medium)
- 310. Minimum Height Trees(Unknown)
- 684. Redundant Connection(Medium)
- 802. Find Eventual Safe States(Medium)
- 834. Sum of Distances in Tree(Unknown)