DSA
    intermediate

    Union-Find (Disjoint Set)

    Union-Find (Disjoint Set)

    Master the Union-Find data structure. Essential for Kruskal's Algorithm, connected components, and cycle detection in undirected graphs.

    ⏱ O(α(n))
    💾 O(n)
    Ready
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    Ready. Enter two disjoint sets to Union.
    50%
    Live Variables
    sets10

    union(x, y)

    Sequence

    Order the steps of union by rank with path compression.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    4 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What is the primary optimization that makes Union-Find nearly constant time?

    Write the code

    Runs your solution

    Number of Provinces

    Given an `isConnected` matrix, return the total number of provinces (groups of connected cities).

    Example Cases

    Input:[[[1,1,0],[1,1,0],[0,0,1]]]
    Output:2
    Input:[[[1,0,0],[0,1,0],[0,0,1]]]
    Output:3
    javascript

    The short version

    Think of social networks. When person A befriends person B, their entire groups of friends merge into one giant community. You can quickly check if two random people are in the same extended network.

    In more depth

    Disjoint Sets

    Union-Find is a data structure that tracks a set of elements partitioned into a number of disjoint (non-overlapping) subsets.

    Operations:

    1.Find: Which group does element X belong to?
    2.Union: Merge the groups containing elements X and Y.

    Optimizations:

    Path Compression: Evaluating 'find' flattens the tree structure.
    Union by Rank/Size: Always attach the smaller tree to the larger one.

    When to reach for this

    • Find connected components in a graph
    • Check if two nodes are connected (fast)
    • Cycle detection in undirected graphs
    • Kruskal's Algorithm for MST

    Interview Questions

    Uber
    Google
    Amazon
    LinkedIn
    Meta
    Amazon
    Meta
    Uber
    Airbnb
    Bloomberg
    Microsoft
    Netflix
    Google
    LinkedIn
    Bloomberg

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required