Sponsored
Sponsored
This approach relies on the characteristic that in a star graph, the center node is connected to all other nodes, meaning it appears in every edge. By counting the occurrence of each node in the edges, the one that appears most frequently is the center node.
Time Complexity: O(1) since it only involves fixed operations.
Space Complexity: O(1) as no additional data structures are used.
1class Solution {
2 public int findCenter(int[][] edges) {
3 int u1 = edges[0][0], v1 = edges[0][1];
4 int u2 = edges[1][0], v2 = edges[1][1];
5 if (u1 == u2 || u1 == v2) return u1;
6 else return v1;
7 }
8}
9
This Java solution uses direct comparisons on the first few nodes of the edge list, replicating the logic from the C solution.
This approach involves using a hashmap or an array to count the degree or frequency of nodes appearing in the edge list. The node with the maximum frequency of appearance will be the center node.
Time Complexity: O(n)
Space Complexity: O(n)
1from collections
This solution leverages a defaultdict to automate counter logic and fetch the node with maximum frequency.