LeetCode: Find Center Of Star Graph Solution
Approach
Way 1: use hashmap to find the node which has edge to all others
Way 2: because there's only one center, check the first two
Implementation
1/**2 * @param {number[][]} edges3 * @return {number}4 */5var findCenter = function (edges) {6 let map = new Map()7 for (const [x, y] of edges) {8 if (!map.has(x)) {9 map.set(x, new Set())10 }11 if (!map.has(y)) {12 map.set(y, new Set())13 }14 map.set(x, map.get(x).add(y))15 map.set(y, map.get(y).add(x))16 }1718 let res19 let max = -Infinity20 for (const [node, set] of map) {21 if (set.size > max) {22 res = node23 max = set.size24 }25 }2627 return res28}2930var findCenter = function (edges) {31 return edges[0].filter(node => edges[1].includes(node))[0]32}
Comments
Loading comments...
Tags
leetcode
graph
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.