-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0952-largest-component-size-by-common-factor.js
More file actions
75 lines (67 loc) · 2.23 KB
/
0952-largest-component-size-by-common-factor.js
File metadata and controls
75 lines (67 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* Largest Component Size By Common Factor
* Time Complexity: O(N * sqrt(M) * alpha(M))
* Space Complexity: O(M)
*/
var largestComponentSize = function (nums) {
let maxValueInNums = 0;
for (let currentNumberValue of nums) {
if (currentNumberValue > maxValueInNums) {
maxValueInNums = currentNumberValue;
}
}
const representativeArray = new Array(maxValueInNums + 1)
.fill(0)
.map((_val, index) => index);
const componentDepth = new Array(maxValueInNums + 1).fill(0);
const findSetRepresentative = (elementItem) => {
if (representativeArray[elementItem] === elementItem) {
return elementItem;
}
representativeArray[elementItem] = findSetRepresentative(
representativeArray[elementItem],
);
return representativeArray[elementItem];
};
const uniteSets = (elementOne, elementTwo) => {
let rootOfOne = findSetRepresentative(elementOne);
let rootOfTwo = findSetRepresentative(elementTwo);
if (rootOfOne !== rootOfTwo) {
if (componentDepth[rootOfOne] < componentDepth[rootOfTwo]) {
representativeArray[rootOfOne] = rootOfTwo;
} else if (componentDepth[rootOfOne] > componentDepth[rootOfTwo]) {
representativeArray[rootOfTwo] = rootOfOne;
} else {
representativeArray[rootOfTwo] = rootOfOne;
componentDepth[rootOfOne]++;
}
return true;
}
return false;
};
for (const numberFromInput of nums) {
for (
let divisorCandidate = 2;
divisorCandidate * divisorCandidate <= numberFromInput;
divisorCandidate++
) {
if (numberFromInput % divisorCandidate === 0) {
uniteSets(numberFromInput, divisorCandidate);
uniteSets(numberFromInput, numberFromInput / divisorCandidate);
}
}
}
const componentSizeTracker = new Map();
let maximumComponentLength = 0;
for (const numberForCounting of nums) {
const componentRoot = findSetRepresentative(numberForCounting);
componentSizeTracker.set(
componentRoot,
(componentSizeTracker.get(componentRoot) || 0) + 1,
);
if (componentSizeTracker.get(componentRoot) > maximumComponentLength) {
maximumComponentLength = componentSizeTracker.get(componentRoot);
}
}
return maximumComponentLength;
};