Union two nodes and report that they are connected.
Acceptance criteria
- 1.#out should show connected.
DSA Tutorial · Union-Find
These 10 tasks go with the Union-Find (Disjoint Sets) chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “Union-Find is the structure for questions about grouping. It cannot tell you the path between two nodes — only whether one exists — and that restriction is what makes it almost free.” .
1.Join two elementsexercise · easy · 10 min
Union two nodes and report that they are connected.
Passes when: #out should show connected.
2.Unrelated stay apartexercise · easy · 10 min · practice plan
Report that two untouched nodes are not connected.
Passes when: #out should show separate.
3.Count componentsexercise · easy · 10 min · practice plan
Report how many groups remain after one union of three nodes.
Passes when: #out should show two groups.
4.Detect a redundant edgeexercise · easy · 10 min · practice plan
Report that joining an already-connected pair adds nothing.
Passes when: #out should show already joined.
5.Chain of unionsexercise · medium · 10 min · practice plan
Join three nodes in a chain and confirm the ends are connected.
Passes when: #out should show connected.
6.Fix union linking the elements not the rootsbug fix · easy · 8 min
Pointing one element at another loses whole groups.
Passes when: #out should show connected.
7.Fix find comparing valuesbug fix · easy · 8 min · practice plan
Comparing the owner entries rather than the roots misreports membership.
Passes when: #out should show separate.
8.Fix the count decremented every timebug fix · medium · 8 min · practice plan
Reducing the count for an existing link undercounts the groups.
Passes when: #out should show two groups.
9.Fix union always reporting successbug fix · easy · 8 min · practice plan
Returning true for an existing link breaks cycle detection.
Passes when: #out should show already joined.
10.Fix find stopping after one hopbug fix · easy · 8 min · practice plan
Following the owner only once misses the true root of a chain.
Passes when: #out should show connected.
Between them these tasks cover find and union, Path compression and Counting components.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.