From 7873828c4c523f98104767a9f1fc70e69611e00f Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Thu, 27 Jun 2024 13:16:44 +0000 Subject: [PATCH] posts: union-find: fix union of same root --- content/posts/2024-06-24-union-find/index.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/content/posts/2024-06-24-union-find/index.md b/content/posts/2024-06-24-union-find/index.md index 2fe1570..7c9435c 100644 --- a/content/posts/2024-06-24-union-find/index.md +++ b/content/posts/2024-06-24-union-find/index.md @@ -142,6 +142,9 @@ _approximate_ height, we can keep the trees balanced when merging them. def union(self, lhs: int, rhs: int) -> int: lhs = self.find(lhs) rhs = self.find(rhs) + # Bail out early if they already belong to the same set + if lhs == rhs: + return lhs # Always keep `lhs` as the taller tree if (self._rank[lhs] < self._rank[rhs]) lhs, rhs = rhs, lhs