|
| 1 | +from random import randint |
| 2 | +from string import ascii_lowercase |
| 3 | +from typing import Iterable, List |
| 4 | + |
| 5 | + |
| 6 | +class DSU: |
| 7 | + """ |
| 8 | + Disjoint set system with rank and path compression heuristics |
| 9 | +
|
| 10 | + Memory: |
| 11 | + creation - O(n) |
| 12 | + 'find' - O(log(n)) |
| 13 | + 'union' - O(log(n)) |
| 14 | +
|
| 15 | + Time: |
| 16 | + creation - O(n) |
| 17 | + 'find' - O(log(n)) |
| 18 | + 'union' - O(log(n)) |
| 19 | +
|
| 20 | + On average, operations 'find' and 'union' take O(1) time and space |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, nodes: Iterable): |
| 24 | + self.parent = {n: n for n in nodes} |
| 25 | + self.rank = {n: 1 for n in nodes} |
| 26 | + |
| 27 | + def find(self, a: int) -> int: |
| 28 | + if a != self.parent[a]: |
| 29 | + self.parent[a] = self.find(self.parent[a]) |
| 30 | + return self.parent[a] |
| 31 | + |
| 32 | + def union(self, a: int, b: int): |
| 33 | + a_root = self.find(a) |
| 34 | + b_root = self.find(b) |
| 35 | + |
| 36 | + if a_root == b_root: |
| 37 | + return |
| 38 | + |
| 39 | + if self.rank[a_root] > self.rank[b_root]: |
| 40 | + self.parent[b_root] = a_root |
| 41 | + elif self.rank[a_root] < self.rank[b_root]: |
| 42 | + self.parent[a_root] = b_root |
| 43 | + else: |
| 44 | + if randint(0, 1) & 1: |
| 45 | + a_root, b_root = b_root, a_root |
| 46 | + self.parent[b_root] = a_root |
| 47 | + self.rank[a_root] += 1 |
| 48 | + |
| 49 | + |
| 50 | +class Solution: |
| 51 | + """ |
| 52 | + Time: O(n) |
| 53 | + Memory: O(n) |
| 54 | + """ |
| 55 | + |
| 56 | + EQUAL = '=' |
| 57 | + NOT_EQUAL = '!' |
| 58 | + |
| 59 | + def equationsPossible(self, equations: List[str]) -> bool: |
| 60 | + dsu = DSU(ascii_lowercase) |
| 61 | + |
| 62 | + for eq in equations: |
| 63 | + i, sign, _, j = list(eq) |
| 64 | + if sign == self.EQUAL: |
| 65 | + dsu.union(i, j) |
| 66 | + |
| 67 | + for eq in equations: |
| 68 | + i, sign, _, j = list(eq) |
| 69 | + if sign == self.NOT_EQUAL and dsu.find(i) == dsu.find(j): |
| 70 | + return False |
| 71 | + |
| 72 | + return True |
0 commit comments