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[][]} edges
3 * @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 }
17
18 let res
19 let max = -Infinity
20 for (const [node, set] of map) {
21 if (set.size > max) {
22 res = node
23 max = set.size
24 }
25 }
26
27 return res
28}
29
30var 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.

Next Post

LeetCode: Check If One String Swap Can Make Strings Equal

HoningJS

Search Posts