DDSA Solutions

1791. Find Center of Star Graph

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

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