Leetcode 1791. Find Center of Star Graph
Leetcode Problem 1791: Find Center of Star Graph
There is an undirected star graph consisting of n
nodes labeled from 1
to n
. A star graph is a graph where there is one center node and exactly n-1
edges that connect the center node with every other node.
You are given a 2D integer array edges
where each edges[i] = [u_i, v_i]
indicates that there is an edge between the nodes u_i
and v_i
. Return the center of the given star graph.
n
?
n
can be reasonably small to medium-sized, typically in the order of up to a few thousand.The star graph has one center node connected to all other nodes. This means that the center node will appear in every edge of the graph. To identify the center node:
#include <vector>
using namespace std;
class Solution {
public:
int findCenter(vector<vector<int>>& edges) {
// Check the first two edges to find the common node which is the center
int node1 = edges[0][0];
int node2 = edges[0][1];
// The center must be among node1 or node2; it will be whichever appears in the second edge.
if (edges[1][0] == node1 || edges[1][1] == node1) {
return node1;
} else {
return node2;
}
}
};
node1
or node2
) is present in the second edge. The one that appears in the second edge is the center.The time complexity of this solution is (O(1)) because:
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?