1791. Find Center of Star Graph

Dare2Solve

Dare2Solve

1791. Find Center of Star Graph
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

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

Code

C++

class Solution {
public:
    int findCenter(vector<vector<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;
    }
};

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;
};