1791. Find Center of Star Graph
Problem Description
The task involves identifying the center of an undirected star graph composed of n
nodes, which are numbered from 1
to n
. A star graph has one central node and exactly n - 1
edges connecting this central node to all other nodes. In simpler terms, a star graph looks like a star, where every point or tip of the star is connected to a central or middle point.
You are given an array edges
, where each element edges[i]
represents an edge in the graph and consists of two integers [u_i, v_i]
. These integers denote an edge connecting the nodes u_i
and v_i
. The goal is to figure out which node is the center of the star graph.
Intuition
To solve this problem, we can start by noticing that in a star graph, the center node will be the one shared by all the edges. Since we know that this graph is a star graph, we can conclude that the center must be one of the nodes from the first edge described in the edges
array.
We can take the first edge edges[0]
, which is represented by [u1, v1]
. This edge must be connected to the center because every edge in a star graph connects directly to the center. To find the center, we simply need to check which node from the first edge is also present in the second edge edges[1]
.
If the first node u1
of the first edge edges[0]
is present in the second edge edges[1]
, then u1
is the center of the graph. If not, then the second node v1
of the first edge must be the center. Therefore, with just a simple comparison of two edges, we can determine the center of the star graph.
This approach works because of two key properties of the star graph:
- The center node is connected to all other nodes.
- There is only one center node in a star graph.
Given these properties, the common node between any two edges in the given star graph must be the center.
Learn more about Graph patterns.
Solution Approach
The implementation of the solution is quite straightforward and doesn't require complex data structures, patterns, or algorithms. The simplicity of the problem stems from the unique structure of the star graph where the center node is the one common node in all edges.
Here is a walk-through of the implementation based on the provided Python code:
class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return edges[0][0] if edges[0][0] in edges[1] else edges[0][1]
-
We define a function
findCenter
which takes as an input parameteredges
, a list of lists, with each sublist representing an edge in the star graph. -
The function returns either
edges[0][0]
oredges[0][1]
. These are the two nodes in the first edge. One of these must be the center because every edge in the graph must contain the center node due to the definition of a star graph. -
We use a simple
if
statement to check if the first node of the first edgeedges[0][0]
is also in the second edgeedges[1]
. Ifedges[0][0]
is indeed in the second edge, we return it as it is the center. Otherwise, we return the second node from the first edgeedges[0][1]
.
This implementation essentially leverages the property that the second edge must also contain the center of the star graph. In other words, we are using the fact that the center node will be the only node that repeats in the first two edges.
No additional algorithms or data structures are required, as the star graph's structure ensures that comparing the first two edges is sufficient to identify the center node.
What makes it efficient is that we only need to look at the first two edges. We don't need to check the entire edges
list, so the time complexity is constant, O(1), since the number of operations does not depend on the number of edges or nodes in the graph.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's use a small example to illustrate the solution approach. Suppose we have a star graph with 4 nodes which results in 3 edges and we are given the edges
array representing these edges as:
edges = [[1, 2], [2, 3], [4, 2]]
Based on our solution approach, we know that one of the nodes in edges[0]
, which is [1, 2]
, must be the center of the star graph. Now we only need to determine which one it is. To do this, we look at edges[1]
, which is [2, 3]
.
Step 1: We identify the nodes in the first edge. They are:
u1
fromedges[0]
is1
v1
fromedges[0]
is2
Step 2: We examine the second edge, which contains:
u2
fromedges[1]
is2
v2
fromedges[1]
is3
Step 3: We determine the common node between the first and second edge:
2
is the common node because it is present in both[1, 2]
and[2, 3]
.
Since the node 2
is common to both edges, we can deduce that 2
is the center of our star graph. Hence, the solution function will return 2
.
The execution of the code using our example edges
array would be as follows:
solution = Solution()
center = solution.findCenter(edges)
print(center) # This will print 2, as node 2 is the center of the star graph
Our analysis confirms that the first two edges are sufficient to determine the center and that the function findCenter
behaves as expected. It returns 2
, which is the common node in both edges, and thus the center of the given star graph.
Solution Implementation
1# Import the List type from typing module for type annotations
2from typing import List
3
4class Solution:
5 def findCenter(self, edges: List[List[int]]) -> int:
6 # The center of a star graph is connected to all other nodes.
7 # The center must be one of the two vertices in the first edge.
8 # Check if the first vertex of the first edge is in the second edge:
9 if edges[0][0] in edges[1]:
10 # If the first vertex is in the second edge,
11 # it's the center and return it.
12 return edges[0][0]
13 else:
14 # Otherwise, the second vertex of the first edge is the center, return it.
15 return edges[0][1]
16
1class Solution {
2 public int findCenter(int[][] edges) {
3 // Extract the first edge's vertices
4 int firstVertexOfFirstEdge = edges[0][0];
5 int secondVertexOfFirstEdge = edges[0][1];
6
7 // Extract the second edge's vertices
8 int firstVertexOfSecondEdge = edges[1][0];
9 int secondVertexOfSecondEdge = edges[1][1];
10
11 // The center of a star graph is connected to all other vertices.
12 // Therefore, the center must be one of the vertices in the first edge.
13 // We check if the first vertex of the first edge is the same as any vertex in the second edge.
14 if (firstVertexOfFirstEdge == firstVertexOfSecondEdge || firstVertexOfFirstEdge == secondVertexOfSecondEdge) {
15 // If true, then the first vertex of the first edge is the center.
16 return firstVertexOfFirstEdge;
17 } else {
18 // If not, then the second vertex of the first edge must be the center.
19 return secondVertexOfFirstEdge;
20 }
21 }
22}
23
1#include <vector>
2
3class Solution {
4public:
5 // Finds the center of a star graph.
6 // The star graph has one node in the center connected to all other nodes.
7 // edges are provided as pairs indicating two nodes that are connected.
8 int findCenter(vector<vector<int>>& edges) {
9 // Extract node values from the first edge
10 int firstNodeOfFirstEdge = edges[0][0];
11 int secondNodeOfFirstEdge = edges[0][1];
12
13 // Extract node values from the second edge
14 int firstNodeOfSecondEdge = edges[1][0];
15 int secondNodeOfSecondEdge = edges[1][1];
16
17 // The center node is connected to every other node, so it will appear in both edges.
18 // If the first node of the first edge is the center, it should be equal to either node of the second edge.
19 // Otherwise, the center is the other node of the first edge.
20 if (firstNodeOfFirstEdge == firstNodeOfSecondEdge || firstNodeOfFirstEdge == secondNodeOfSecondEdge) {
21 // The first node of the first edge is the center.
22 return firstNodeOfFirstEdge;
23 } else {
24 // The second node of the first edge is the center.
25 return secondNodeOfFirstEdge;
26 }
27 }
28};
29
1// Finds the center of a star graph
2// @param {number[][]} edges - A 2D array containing pairs of connected nodes
3// @returns {number} The value of the central node
4function findCenter(edges: number[][]): number {
5 // Loop through each node in the first pair of connected nodes
6 for (let node of edges[0]) {
7 // Check if the node is also a part of the second pair of connected nodes
8 if (edges[1].includes(node)) {
9 // If it is, then it is the center node, return this node
10 return node;
11 }
12 }
13 // If not found (though theoretically for a star graph it should always return in the loop), return 0
14 // As per LeetCode's constraints, there will always be a center, so the function will always return within the loop
15 return 0;
16}
17
Time and Space Complexity
The time complexity of the given code is O(1)
. This is because the code only checks for the presence of edges[0][0]
in edges[1]
, which is a constant-time operation since it involves two fixed index accesses and one in
operation on a list with only two elements.
The space complexity of the code is also O(1)
. The code does not use any additional space that grows with the input size. It only uses a fixed amount of space for the variables in the function, regardless of the input size.
Learn more about how to find time and space complexity quickly using problem constraints.
A person thinks of a number between 1 and 1000. You may ask any number questions to them, provided that the question can be answered with either "yes" or "no".
What is the minimum number of questions you needed to ask so that you are guaranteed to know the number that the person is thinking?
Recommended Readings
https algomonster s3 us east 2 amazonaws com cover_photos graph svg Graph Fundamentals Tree with 0 cycle At this point you should be pretty familiar with trees A tree is a special kind of graph a connected acyclic cycle less graph A graph may contain cycle s and nodes could
LeetCode Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way we
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Want a Structured Path to Master System Design Too? Don’t Miss This!