🎨 Try our Free AI Image Generation Feature

1791. Find Center of Star Graph

avatar
Dare2Solve

1 year ago

1791. Find Center of Star Graph

Intuition

A star graph has one central node that is connected to all other nodes. Therefore, any two edges in the graph must share this central node. By examining the nodes in the first two edges, we can determine which node is the center.

Approach

  1. Extract the nodes from the first two edges.
  2. Check which node is common between these two edges.
  3. Return the common node as the center of the star graph.

Complexity

  • Time Complexity: O(1), since we only need to check the first two edges to determine the center.
  • Space Complexity: O(1), as no additional space is required beyond a few variables.

Code

C++

class Solution {
public:
    int findCenter(vector>& edges) {
        int a = edges[0][0];
        int b = edges[0][1];
        int c = edges[1][0];
        int d = edges[1][1];
        return (a == c || b == c) ? c : d;
    }
};

Python

class Solution:
    def findCenter(self, edges: List[List[int]]) -> int:
        a, b = edges[0]
        c, d = edges[1]
        return c if a == c or b == c else d

Java

class Solution {
    public int findCenter(int[][] edges) {
        int a = edges[0][0];
        int b = edges[0][1];
        int c = edges[1][0];
        int d = edges[1][1];
        return (a == c || b == c) ? c : d;
    }
}

JavaScript

/**
 * @param {number[][]} edges
 * @return {number}
 */
var findCenter = function (edges) {
    var [a, b] = edges[0];
    var [c, d] = edges[1];
    return a === c || b === c ? c : d;
};