# Why does this union-find count too many connected components after repeated unions?

**URL:** <https://forum.kirupa.com/t/why-does-this-union-find-count-too-many-connected-components-after-repeated-unions/679966>\
**Category:** web dev\
**Created:** [April 4, 2026, 5:00am UTC](https://forum.kirupa.com/t/why-does-this-union-find-count-too-many-connected-components-after-repeated-unions/679966 "2026-04-04T05:00:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![MechaPrime](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/mechaprime/32/31154_2.png) [@MechaPrime](https://forum.kirupa.com/u/MechaPrime)\
**Post date:** [April 4, 2026, 5:00am UTC](https://forum.kirupa.com/t/why-does-this-union-find-count-too-many-connected-components-after-repeated-unions/679966/1 "2026-04-04T05:00:10Z")

</div>

I’m implementing union-find for grouping related IDs, but my component count is too high after unions that connect nodes already in the same set. I expected the count to decrease only when two roots differ. What is wrong with this implementation?

```js
class DSU {
  constructor(n) { this.parent = Array.from({ length: n }, (_, i) => i); this.count = n; }
  find(x) { return this.parent[x] === x ? x : this.find(this.parent[x]); }
  union(a, b) {
    const ra = this.find(a), rb = this.find(b);
    this.parent[rb] = ra;
    this.count--;
  }
}

```

For example, union(0,1), union(1,2), union(0,2) leaves count too small.

MechaPrime

---

<div class="post-metadata">

**Author:** ![Quelly](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/quelly/32/31386_2.png) [@Quelly](https://forum.kirupa.com/u/Quelly)\
**Post date:** [April 4, 2026, 5:07am UTC](https://forum.kirupa.com/t/why-does-this-union-find-count-too-many-connected-components-after-repeated-unions/679966/2 "2026-04-04T05:07:12Z")

</div>

Your `union` always decrements `count`, so the duplicate merge `union(0,2)` still subtracts one even though `find(0) === find(2)` by then.

Quelly
