-
Notifications
You must be signed in to change notification settings - Fork 0
/
numSimilarGroups.ts
46 lines (36 loc) · 996 Bytes
/
numSimilarGroups.ts
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
import { UnionFindWithRank } from 'classes/UnionFindWithRank'
// <Union Find>
// Time: O(n^2 * (m + α(n))), α() is the inverse Ackermann function
// Space: O(n)
// n for the number of strings
// m for the length of the strings
function isSimilar(str1: string, str2: string, length: number): boolean {
let diff = 0
for (let i = 0; i < length; ++i) {
if (str1[i] !== str2[i]) {
++diff
if (diff > 2) {
return false
}
}
}
return true
}
function numSimilarGroups(strs: string[]): number {
// edge cases
if (!strs.length) {
return 0
}
const n = strs.length
const m = strs[0].length
const uf = new UnionFindWithRank(n)
for (let i = 0; i < n; ++i) {
for (let j = i + 1; j < n; ++j) {
if (isSimilar(strs[i], strs[j], m)) {
uf.union(i, j)
}
}
}
return uf.getCount()
}
export { numSimilarGroups }