Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Graphs/Union-Find (Disjoint Set)

Technique · CP 2400+

DSU with Rollback / Offline Dynamic Connectivity

Union by size with no path compression, so each union can be undone from a stack. Put each edge's lifetime on a segment tree over time and DFS that tree, uniting on entry and rolling back on exit. This answers connectivity under insertions and deletions offline in O(q log q log n).

Learn firstUnion-Find (Disjoint Set)Offline Query ProcessingSegment Tree / Fenwick (BIT)
0%
mastery
0/5 solved
Practise nextDynamic Connectivity
IdeaPracticePitfalls

Recognise it

The signal

edges are added AND removed, interleaved with connectivity/component/bipartiteness queries

  1. 1Brute force

    Rebuild the DSU or BFS after every change: O(q(n + m)).

  2. 2The observation

    A DSU cannot delete.

  3. 3Why it works

    At each segment-tree node the DSU holds exactly the edges alive throughout that node's time interval, and rollback restores the parent array exactly.

Reach for it when

  • +all queries known in advance

Not when

  • ×insertions only (plain DSU)
  • ×deletions only (reverse time: offline-queries)
  • ×forced-online queries

Practice

Next

Dynamic Connectivity

0/5 solved
  • Dynamic ConnectivityCSESHard
  • Extending Set of PointsCodeforces2600
  • EnvyCodeforces2300
  • Bipartite CheckingCodeforces2500
  • Forced Online Queries ProblemCodeforces2600

Pitfalls

Misconceptions

  • !path compression breaks rollback
  • !an edge alive over [l, r) goes into O(log q) nodes, not one
Go deeper1 combinations · resources

Combinations

  • DSU with Rollback / Offline Dynamic Connectivity+Segment Tree / Fenwick (BIT)+Offline Query Processing

    add edge / remove edge / count components (or check bipartiteness) with all operations given upfront

    DSU with Rollback / Offline Dynamic Connectivity:
    unite on entry, roll back on exit
    Segment Tree / Fenwick (BIT):
    a segment tree over time storing each edge in the O(log q) nodes covering its lifetime
    Offline Query Processing:
    every add/remove/query must be known before processing

    Dynamic ConnectivityExtending Set of PointsBipartite Checking

Resources

  • Graph Theory playlistWilliam Fiset · video
  • Graph TraversalUSACO Guide · course
  • Disjoint Set Unioncp-algorithms · article
  • Dijkstracp-algorithms · article
  • Topological sortingcp-algorithms · article
  • Shortest paths visualizerVisuAlgo · tool
  • Graph cheatsheetTech Interview Handbook · article
TodayReviewPatternsProblems