Skip to content
Learn Netverks

Lesson

Step 33/36 92% through track

union-find-preview

Union-Find preview

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Union-Find preview: data structure and algorithm concepts with complexity analysis and interview-ready C++ examples.

Optimization problems split into overlapping subproblems (DP) or local choices (greedy)—pick the right paradigm.

You will apply Union-Find preview in contexts like: Interview loops, performance tuning, and foundational CS courses.

Compile and run C++17 snippets in the playground (`int main`, `std::cout`); after each run, state time and space complexity before moving on.

Toward the end—consolidate before AI literacy and capstone interview prep.

Union-Find (Disjoint Set Union) tracks connected components with find and union—nearly O(1) amortized with path compression and union by rank. Used in Kruskal MST, network connectivity.

Operations

  • find(x) — representative of x's set
  • union(a,b) — merge sets containing a and b
  • connected(a,b) — find(a) == find(b)

Simple implementation

#include 
#include 

struct DSU {
    std::vector p;
    DSU(int n) : p(n) { for (int i = 0; i < n; ++i) p[i] = i; }
    int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }
    void unite(int a, int b) { a = find(a); b = find(b); if (a != b) p[a] = b; }
};

int main() {
    DSU dsu(5);
    dsu.unite(0, 1); dsu.unite(2, 3);
    std::cout << (dsu.find(0) == dsu.find(1) ? "same\n" : "diff\n");
    return 0;
}

Kruskal preview

Sort edges by weight; add edge if endpoints in different sets—MST greedy with DSU.

Important interview questions and answers

  1. Q: Path compression?
    A: During find, point nodes directly to root—flattens tree.
  2. Q: Union by rank/size?
    A: Attach smaller tree under larger—keeps depth small.

Self-check

  1. What do find and union do?
  2. Why DSU helps Kruskal MST?

Tip: Path compression in find is one line that impresses in DSU interviews.

Interview prep

Operations?

find representative, union sets—near O(1) amortized with compression.

Kruskal?

Add light edges if endpoints in different sets.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Connected components?
  • Kruskal link?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump