One minute
Leetcode 1791
1791. Find Center of Star Graph
This solution is straightforward.
- We first make an array called
nodeswithedges + 1values. We neededges + 1values becauselen(edges)is the number of edge nodes, and the+ 1is for the center node. We only neededges + 1nodes because the nodes are from1...n. - Then we loop through
edgesand get eachedge.edge[0]andedge[1]are the two values given per edge. One of them is the center node, and the other one is the edge. We add one tonode[edge[0]]andnode[edge[1]]. - Inside the loop we check whether
nodes[edge[0]]andnodes[edge[1]]equals2because the only node that repeats twice is the center node. And ifnodes[edge[0]] == 2ornodes[edge[1]] == 2we should return the center node.
(Note: The problem says 3 <= n <= 10^5, but if it didn’t at the end the code returns edge[0][0] becuase of the test case len(edges) == 1)
func findCenter(edges [][]int) int {
nodes := make([]int, len(edges) + 2)
for _, edge := range edges {
nodes[edge[0]]++
nodes[edge[1]]++
if nodes[edge[0]] == 2 {
return edge[0]
}
if nodes[edge[1]] == 2 {
return edge[1]
}
}
return edges[0][0]
}
Read other posts