-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0839-similar-string-groups.js
More file actions
81 lines (71 loc) · 1.97 KB
/
0839-similar-string-groups.js
File metadata and controls
81 lines (71 loc) · 1.97 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
76
77
78
79
80
81
/**
* Similar String Groups
* Time Complexity: O(N^2 * L + N * alpha(N))
* Space Complexity: O(N)
*/
var numSimilarGroups = function (strs) {
const totalStrings = strs.length;
const parentArray = Array.from(
{ length: totalStrings },
(_, elementIndex) => elementIndex,
);
const depthArray = new Array(totalStrings).fill(0);
const retrieveRoot = (elementIndex) => {
if (parentArray[elementIndex] === elementIndex) {
return elementIndex;
}
parentArray[elementIndex] = retrieveRoot(parentArray[elementIndex]);
return parentArray[elementIndex];
};
const uniteSets = (idxA, idxB) => {
const rootA = retrieveRoot(idxA);
const rootB = retrieveRoot(idxB);
if (rootA === rootB) {
return;
}
if (depthArray[rootA] < depthArray[rootB]) {
parentArray[rootA] = rootB;
} else if (depthArray[rootB] < depthArray[rootA]) {
parentArray[rootB] = rootA;
} else {
parentArray[rootB] = rootA;
depthArray[rootA]++;
}
};
const similarityCheck = (stringOne, stringTwo) => {
if (stringOne === stringTwo) {
return true;
}
let differenceCount = 0;
const stringLength = stringOne.length;
for (let charPosition = 0; charPosition < stringLength; charPosition++) {
if (stringOne[charPosition] !== stringTwo[charPosition]) {
differenceCount++;
if (differenceCount > 2) {
return false;
}
}
}
return differenceCount === 2;
};
for (let indexOuter = 0; indexOuter < totalStrings; indexOuter++) {
for (
let indexInner = indexOuter + 1;
indexInner < totalStrings;
indexInner++
) {
if (similarityCheck(strs[indexOuter], strs[indexInner])) {
uniteSets(indexOuter, indexInner);
}
}
}
const uniqueRoots = new Set();
for (
let currentElement = 0;
currentElement < totalStrings;
currentElement++
) {
uniqueRoots.add(retrieveRoot(currentElement));
}
return uniqueRoots.size;
};