2Brute2Best
🔥0
03

Grouping / equivalence (Union-Find (DSU) Sub-pattern)

Merge items that are declared equal (or connected by a rule), then process each group together.

Signals in the problem statement
  • ›

    "a==b" / "a!=b" equations

  • ›

    "accounts with a common email belong to the same person"

  • ›

    "you can swap the characters at any pair any number of times"

  • ›

    "strings are similar if …"

What makes it different

Equality Equations unions every == first, then checks that no != pair shares a root (order matters). Accounts Merge maps each email to an id and unions emails within an account. Smallest String With Swaps sorts each group's characters into the group's indices. Similar String Groups unions every pair of similar words (O(n²) pairs) and counts groups.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Satisfiability of Equality Equations
    Basic Anchor·LeetCode #990
    Medium
  2. 2
    Accounts Merge
    Basic Reinforcement·LeetCode #721
    Medium
  3. 3
    Smallest String With Swaps
    Slight Variation·LeetCode #1202
    Medium
  4. 4
    Similar String Groups
    Interview-Level·LeetCode #839
    Hard

Template

equivalence-template.cpp
// Grouping by "is equivalent to": union every given pair, then collect each root's members.
// Uses the DSU from the Union-Find template. Here: Smallest String With Swaps.
string smallestStringWithSwaps(string s, const vector<vector<int>>& pairs) {
    int n = s.size();
    DSU dsu(n);
    for (auto& p : pairs) dsu.unite(p[0], p[1]);  // swaps chain: (0,3) and (3,1) let 0, 1, 3 trade freely
    unordered_map<int, vector<int>> members;       // root → indices in that group, increasing
    for (int i = 0; i < n; i++) members[dsu.find(i)].push_back(i);
    for (auto& [root, idx] : members) {
        string chars;
        for (int i : idx) chars += s[i];
        sort(chars.begin(), chars.end());          // inside a group any arrangement is reachable
        for (int k = 0; k < (int)idx.size(); k++) s[idx[k]] = chars[k];
    }
    return s;
}
Remember this · Union-Find (DSU)
Trigger
Edges arrive one by one, "are these connected?", merge equivalent items, count components, extra edge creating a cycle.
Think
Am I repeatedly merging groups and asking whether two things are in the same group?
Key question
What are the elements, and what does it mean to union two of them?