Support Moving a User Between Groups in a Disjoint Set

Last updated: November 29, 2026

Quick Overview

Design a structure over n users that supports union(a, b), same_group(a, b), group_stats(a) returning the group's size and the sum of its user IDs, and move(a, b), which takes user a out of its group and puts it in b's group.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Design a structure over n users that supports union(a, b), same_group(a, b), group_stats(a) returning the group's size and the sum of its user IDs, and move(a, b), which takes user a out of its group and puts it in b's group.

Google Groups and Workspace membership change constantly, and this screen question tests whether you can extend union-find beyond its textbook form. Standard union-find cannot remove an element, so the interviewer looks for the virtual node trick plus correct aggregate bookkeeping.

What the Interviewer Expects
  • Explains why deleting a node from a union-find tree is unsafe
  • Introduces a user to internal node mapping
  • On move, decrements the old root's aggregates and gives the user a fresh node
  • Keeps aggregates such as size and sum at roots
  • Keeps all operations near-constant amortized
Key Topics to Cover
Union-Find
Data Structure Design
Virtual Nodes
Aggregates
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How much memory do ghost nodes cost after millions of moves, and how would you compact?
  • Support removing a user entirely.
  • Make the aggregate the maximum user ID instead of the sum. What breaks?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Users are 0..n-1.
  • move(a, b) is a no-op if they are already in the same group.
  • group_stats(a) returns (size, sum of IDs) for a's current group....
High-Level Design

The old node of a moved user may be the parent of other nodes, so physically removing it would disconnect them. Instead keep a node_of map from user to internal node. On move, subtract the user's ...


Submit Your Answer
Markdown supported