Facebook Pixel

1791. Find Center of Star Graph

Problem Description

You are given an undirected star graph with n nodes labeled from 1 to n. A star graph is a special type of graph that has one center node connected to all other nodes with exactly n - 1 edges. This means every non-center node is connected only to the center node.

The input is a 2D integer array edges where each edges[i] = [ui, vi] represents an edge between nodes ui and vi. Your task is to find and return the center node of this star graph.

For example, if you have a star graph with 4 nodes where node 2 is the center, the edges would connect node 2 to nodes 1, 3, and 4. The edges array might look like [[1,2], [2,3], [4,2]] or any permutation of these edges.

The solution leverages a key observation: since the center node is connected to all other nodes, it must appear in every edge. Therefore, by examining just the first two edges, we can identify the center - it's the node that appears in both edges. The code checks if the first node of the first edge appears in the second edge; if it does, that's the center. Otherwise, the second node of the first edge must be the center.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

Let's think about the structure of a star graph. By definition, the center node has edges connecting it to every other node in the graph. This means the center node appears in every single edge in our edges array.

Now, consider any two edges from the graph. Since the center must be part of both edges, there will be exactly one node that appears in both. The non-center nodes only have one connection (to the center), so they can't appear in multiple edges.

This leads to a simple insight: we don't need to examine all edges to find the center. Just looking at the first two edges is sufficient! The node that appears in both edges[0] and edges[1] must be the center.

For instance, if edges[0] = [1, 3] and edges[1] = [3, 4], we can see that node 3 appears in both edges, so 3 must be the center.

The algorithm becomes straightforward:

  • Check if edges[0][0] (first node of the first edge) appears in edges[1]
  • If yes, it's the center
  • If no, then edges[0][1] (second node of the first edge) must be the center

This works because one of the two nodes in edges[0] must be the center, and the center must also appear in edges[1]. The beauty of this approach is its simplicity - we solve the problem in O(1) time by examining just two edges rather than processing all n-1 edges.

Learn more about Graph patterns.

Solution Approach

The solution implements the direct comparison approach identified in our intuition. We only need to examine the first two edges to find the center node.

Here's how the implementation works:

  1. Access the first two edges: We look at edges[0] and edges[1], which represent the first two edges in our graph.

  2. Check for the common node:

    • We take the first node from the first edge: edges[0][0]
    • We check if this node appears in the second edge using the in operator: edges[0][0] in edges[1]
    • The in operator checks if edges[0][0] equals either edges[1][0] or edges[1][1]
  3. Return the center:

    • If edges[0][0] is found in edges[1], then it's the center node and we return it
    • Otherwise, edges[0][1] must be the center (since one node from the first edge must be the center, and it must also appear in the second edge)

The entire solution is condensed into a single line using a ternary operator:

return edges[0][0] if edges[0][0] in edges[1] else edges[0][1]

This approach is optimal because:

  • Time Complexity: O(1) - We only check a constant number of values (at most 4 comparisons)
  • Space Complexity: O(1) - We don't use any extra space beyond a few variables

The elegance of this solution lies in its simplicity - by understanding the fundamental property of a star graph (the center appears in every edge), we avoid unnecessary iteration through all edges and solve the problem with minimal operations.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through a concrete example to see how this solution works.

Consider a star graph with 5 nodes where node 3 is the center. The edges array might be:

edges = [[1,3], [3,2], [3,4], [5,3]]

This represents the following star structure:

    1
    |
5---3---2
    |
    4

Step 1: Extract the first two edges

  • edges[0] = [1, 3]
  • edges[1] = [3, 2]

Step 2: Check if the first node of edge[0] appears in edge[1]

  • edges[0][0] = 1
  • Is 1 in [3, 2]?
  • We check: Is 1 == 3? No. Is 1 == 2? No.
  • So 1 is NOT in edges[1]

Step 3: Since edges[0][0] is not in edges[1], return edges[0][1]

  • edges[0][1] = 3
  • Return 3 as the center

Let's verify this is correct by checking another example where the first node IS the center:

edges = [[2,1], [2,3], [4,2]]

Step 1: Extract the first two edges

  • edges[0] = [2, 1]
  • edges[1] = [2, 3]

Step 2: Check if the first node of edge[0] appears in edge[1]

  • edges[0][0] = 2
  • Is 2 in [2, 3]?
  • We check: Is 2 == 2? Yes!
  • So 2 IS in edges[1]

Step 3: Since edges[0][0] is in edges[1], return edges[0][0]

  • Return 2 as the center

The algorithm works because the center node must appear in every edge. By checking just the first two edges, we can identify which node appears in both - that's guaranteed to be our center.

Solution Implementation

1class Solution:
2    def findCenter(self, edges: List[List[int]]) -> int:
3        """
4        Find the center node of a star graph.
5      
6        In a star graph, the center node is connected to all other nodes.
7        Since we have at least 2 edges, the center must appear in both edges.
8      
9        Args:
10            edges: List of edges where each edge is [u, v] representing a connection
11      
12        Returns:
13            The center node of the star graph
14        """
15        # Check if the first node of the first edge appears in the second edge
16        # If yes, it's the center; otherwise, the second node of the first edge is the center
17        if edges[0][0] in edges[1]:
18            return edges[0][0]
19        else:
20            return edges[0][1]
21
1class Solution {
2    /**
3     * Finds the center node of a star graph.
4     * In a star graph, the center node is connected to all other nodes.
5     * Since we have n-1 edges for n nodes, the center must appear in every edge.
6     * Therefore, checking just the first two edges is sufficient.
7     * 
8     * @param edges Array of edges where each edge is represented as [u, v]
9     * @return The center node of the star graph
10     */
11    public int findCenter(int[][] edges) {
12        // Extract nodes from the first edge
13        int firstEdgeNode1 = edges[0][0];
14        int firstEdgeNode2 = edges[0][1];
15      
16        // Extract nodes from the second edge
17        int secondEdgeNode1 = edges[1][0];
18        int secondEdgeNode2 = edges[1][1];
19      
20        // The center node must appear in both edges
21        // Check if firstEdgeNode1 appears in the second edge
22        if (firstEdgeNode1 == secondEdgeNode1 || firstEdgeNode1 == secondEdgeNode2) {
23            return firstEdgeNode1;
24        }
25      
26        // Otherwise, firstEdgeNode2 must be the center
27        return firstEdgeNode2;
28    }
29}
30
1class Solution {
2public:
3    int findCenter(vector<vector<int>>& edges) {
4        // Extract the two nodes from the first edge
5        int firstEdgeNode1 = edges[0][0];
6        int firstEdgeNode2 = edges[0][1];
7      
8        // Extract the two nodes from the second edge
9        int secondEdgeNode1 = edges[1][0];
10        int secondEdgeNode2 = edges[1][1];
11      
12        // The center node must appear in both edges
13        // Check if the first node of the first edge appears in the second edge
14        if (firstEdgeNode1 == secondEdgeNode1 || firstEdgeNode1 == secondEdgeNode2) {
15            return firstEdgeNode1;
16        }
17      
18        // Otherwise, the second node of the first edge must be the center
19        return firstEdgeNode2;
20    }
21};
22
1/**
2 * Finds the center node of a star graph given its edges.
3 * In a star graph, the center node is connected to all other nodes.
4 * 
5 * @param edges - Array of edges where each edge is represented as [node1, node2]
6 * @returns The center node of the star graph
7 */
8function findCenter(edges: number[][]): number {
9    // Check each node in the first edge
10    for (const node of edges[0]) {
11        // If this node also appears in the second edge, it must be the center
12        // (since the center connects to all other nodes)
13        if (edges[1].includes(node)) {
14            return node;
15        }
16    }
17  
18    // This return should never be reached in a valid star graph
19    // TypeScript requires all code paths to return a value
20    return -1;
21}
22

Time and Space Complexity

The time complexity is O(1). The algorithm performs a constant number of operations regardless of the input size. It accesses two elements from edges[0] and checks if edges[0][0] exists in edges[1] (which contains exactly 2 elements), resulting in a fixed number of comparisons.

The space complexity is O(1). The algorithm uses only a constant amount of extra space. No additional data structures are created, and the space usage doesn't scale with the input size. The only operations performed are direct element access and membership checking on fixed-size lists.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Assuming the in operator works on integers instead of lists

A common misconception is thinking that edges[0][0] in edges[1] checks if the integer edges[0][0] exists as a value somewhere in edges[1]. However, edges[1] is a list with exactly two elements, and the in operator checks if edges[0][0] equals one of those elements.

Incorrect understanding:

# Some might think this checks if 2 appears "somewhere" in [3, 2]
# But it actually checks if 2 == 3 or 2 == 2
edges[0][0] in edges[1]  # where edges[0][0] = 2, edges[1] = [3, 2]

2. Over-complicating with unnecessary data structures

Many developers instinctively reach for frequency counting or set operations:

Overcomplicated approach:

def findCenter(self, edges: List[List[int]]) -> int:
    # Unnecessary: counting all node frequencies
    freq = {}
    for u, v in edges:
        freq[u] = freq.get(u, 0) + 1
        freq[v] = freq.get(v, 0) + 1
  
    # Find node with frequency n-1
    for node, count in freq.items():
        if count == len(edges):
            return node

This works but has O(n) time complexity and O(n) space complexity, when O(1) for both is achievable.

3. Not handling edge cases mentally

While the problem guarantees a valid star graph, developers might worry about:

  • What if there are fewer than 2 edges? (Problem guarantees n β‰₯ 3, so at least 2 edges exist)
  • What if no common node exists? (Invalid star graph, won't happen per problem constraints)

Solution to avoid pitfalls:

  1. Trust the problem constraints: The problem guarantees a valid star graph, so defensive programming is unnecessary.

  2. Think before coding: Recognize that in a star graph, the center appears in ALL edges, so checking just two edges is sufficient.

  3. Keep it simple: The one-liner solution is both correct and optimal:

return edges[0][0] if edges[0][0] in edges[1] else edges[0][1]
  1. Alternative clear implementation if the one-liner seems confusing:
def findCenter(self, edges: List[List[int]]) -> int:
    # Extract nodes from first two edges
    first_edge = edges[0]
    second_edge = edges[1]
  
    # Check which node from the first edge appears in the second
    if first_edge[0] == second_edge[0] or first_edge[0] == second_edge[1]:
        return first_edge[0]
    else:
        return first_edge[1]

This explicit comparison makes the logic clearer while maintaining O(1) complexity.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which algorithm should you use to find a node that is close to the root of the tree?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More