union_find

def findRoot(node: int, nodeToParent: dict) -> int:
  root = nodeToParent[node]
  while root != nodeToParent[root]:
    root = nodeToParent[root]
  return root

def union(nodeX: int, nodeY: int, nodeToParent: dict) -> bool:
  rootX = findRoot(nodeX, nodeToParent)
  rootY = findRoot(nodeY, nodeToParent)
  if rootX != rootY:
    nodeToParent[rootX] = rootY
    return True
  else:
    return False

# use dictionary instead of array to represent the parent mapping
nodeToParent = {x:x for x in range(n)}

# calculate number of components in the graph
numComponents = sum([1 for k,v in nodeToParent.items() if k == v])

Reviewed

547.Friend-Circlesarrow-up-right (M)

TODO

200.Number-of-Islandsarrow-up-right (H-) 305.Number-of-Islands-IIarrow-up-right (H-) 130.Surrounded-Regionsarrow-up-right (H-) 128.Longest-Consecutive-Sequencearrow-up-right (H-) 684.Redundant-Connectionarrow-up-right (M) 685.Redundant-Connection-IIarrow-up-right (H) 721.Accounts-Mergearrow-up-right (M+) 765.Couples-Holding-Handsarrow-up-right (H-) 785.Is-Graph-Bipartitearrow-up-right (M+) 924.Minimize-Malware-Spreadarrow-up-right (H-) 947.Most-Stones-Removed-with-Same-Row-or-Columnarrow-up-right (M+) 959.Regions-Cut-By-Slashesarrow-up-right (H-) 990.Satisfiability-of-Equality-Equationsarrow-up-right (M+) 1061.Lexicographically-Smallest-Equivalent-Stringarrow-up-right (M) 1101.The-Earliest-Moment-When-Everyone-Become-Friendsarrow-up-right (M+) 1202.Smallest-String-With-Swapsarrow-up-right (M+) 1319.Number-of-Operations-to-Make-Network-Connectedarrow-up-right (M+) 1632.Rank-Transform-of-a-Matrixarrow-up-right (H) 1631.Path-With-Minimum-Effortarrow-up-right (H-) 1724.Checking-Existence-of-Edge-Length-Limited-Paths-IIarrow-up-right (H+) 1722.Minimize-Hamming-Distance-After-Swap-Operationsarrow-up-right (M+) 803.Bricks-Falling-When-Hitarrow-up-right (H) 1970.Last-Day-Where-You-Can-Still-Crossarrow-up-right (H-)

Patterns

  • Suitable in a dynamically changing graph.

    • Complexity: O(lgn)

    • Example problems: Number of Island II, find weakly connected components in directed graph, find connected components in undirected graph

Prime Factors

952.Largest-Component-Size-by-Common-Factorarrow-up-right (H) 1627.Graph-Connectivity-With-Thresholdarrow-up-right (M+) 1998.GCD-Sort-of-an-Arrayarrow-up-right (H-)

MST

1135.Connecting-Cities-With-Minimum-Costarrow-up-right (M+) 1168.Optimize-Water-Distribution-in-a-Villagearrow-up-right (H-) 1489.Find-Critical-and-Pseudo-Critical-Edges-in-Minimum-Spanning-Treearrow-up-right (H) 1579.Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversablearrow-up-right (H-) 1584.Min-Cost-to-Connect-All-Pointsarrow-up-right (H-)

Last updated