Flower Planting With No Adjacent LeetCode solution in JavaScript

1
/**
2
* @param {number} n
3
* @param {number[][]} paths
4
* @return {number[]}
5
*/
6
var gardenNoAdj = function (n, paths) {
7
//if n is less than or equal to four just return an array of size n from 1 to n
8
if (n <= 4) {
9
let arr = [];
10
let count = 1;
11
while (arr.length < n) {
12
arr.push(count);
13
count++;
14
}
15
return arr;
16
}
17
//if there are no gardens connecting to each other then just return an array of size n with ones
18
if (paths.length === 0) return new Array(n).fill(1);
19

20
//because we have three possible paths connecting to gardens and 4 flowers we know that this problems is possible because our graph is of degree 3 and we have D + 1 flowers
21
//to solve
22
let adjList = {};
23
// create an array filled with ones so if there is a garden with no path just fill with one
24
let result = new Array(n).fill(1);
25
let garden = new Set([1, 2, 3, 4]);
26

27
//create adj list from the paths
28
paths.forEach((path) => {
29
let first = path[0];
30
let second = path[1];
31

32
if (first in adjList) adjList[first].neighbors.add(second);
33
else {
34
adjList[first] = new Fnode(second);
35
}
36

37
if (second in adjList) adjList[second].neighbors.add(first);
38
else {
39
adjList[second] = new Fnode(first);
40
}
41
});
42

43
for (let node in adjList) {
44
//every node
45
let current = adjList[node];
46

47
//create a set of invalid flowers, flowers you can't use because they are part of
48
//the other gardens this one is connected to.
49
let invalidFlower = new Set();
50

51
//iterate over the neighbors to find what type of flower they have and if it is not
52
//null included in the invalid flowers set
53
current.neighbors.forEach((neighbor) => {
54
if (adjList[neighbor]["flower"] !== null) {
55
invalidFlower.add(adjList[neighbor]["flower"]);
56
}
57
});
58

59
//create our possible value or better said our value because we will use the first one
60
//we obtain.
61
let possibleFlower;
62

63
//we iterate over over our garden {1,2,3,4}
64
for (let flower of garden) {
65
//and if our flower is not part of the invalid flowers;
66
if (!invalidFlower.has(flower)) {
67
//we have found a possible flower we can use
68
possibleFlower = flower;
69
//we break because this is the only one we need
70
break;
71
}
72
}
73
// we add our flower to current so that we dont use it in the future
74
current.flower = possibleFlower;
75

76
//and update our result
77
result[node - 1] = possibleFlower;
78
}
79
//we return our result
80
return result;
81
};
82

83
//create a Flower class just for simplicity
84
class Fnode {
85
constructor(neighbor) {
86
this.flower = null;
87
this.neighbors = new Set([neighbor]);
88
}
89
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0