Python Hard Union Find
\nclass UnionFind:\n\n    def __init__(self):\n        self.par = {}\n        self.comp = 0\n\n    def union(self, a, b):\n        ua, ub = self.find(a), self.f
```\nclass UnionFind:\n\n    def __init__(self):\n        self.par = {}\n        self.comp = 0\n\n    def union(self, a, b):\n        ua, ub = self.find(a), self.find(b)\n        if ua == ub:\n            return \n\n        self.comp -= 1\n        self.par[ua] = ub\n\n\n    def find(self, a):\n        if a not in self.par:\n            self.par[a] = a\n            self.comp += 1\n\n        while self.par[a] != a:\n            self.par[a] = self.par[self.par[a]]\n            a = self.par[a]\n            \n        return self.par[a]\n\nclass Solution:\n    def sumImbalanceNumbers(self, nums: List[int]) -> int:\n        ans = 0\n        N = len(nums)\n\n        for i in range(N):\n            uf = UnionFind()\n            seen = set()\n\n            for j in range(i, N):\n                seen.add(nums[j])\n                uf.find(nums[j])\n\n                for k in [nums[j] - 1, nums[j] + 1]:\n                    if k in seen:\n                        uf.union(nums[j], k)\n\n                ans += uf.comp - 1\n\n        return ans\n\n\n\n```
['Python3']