Chapter 16: Sets and Union-Find

Data Structures and Algorithms with C · Study Questions
Disjoint setsArray representationAnalysisWeighting ruleCollapsing ruleApplicationsSummary
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Disjoint Sets

Question 1: How Many Sets?

How many sets does the array parent = [2, −1, −1, 1, 2, 3, −1, 6] describe, and what does find1(5) return?

C: The cells with negative values are 1, 2 and 6: three roots, three sets ({1, 3, 5}, {0, 2, 4}, {6, 7}). The path from 5 is 5 → 3 → 1, and since parent[1] = −1, 1 is returned (2 steps). A stops after the first step; 3 is not a root because it has a parent.

Output Question · Array Representation

Question 2: A Vertex Instead of a Root

What does the code below print? The aim of the last union is to merge the sets of 0 and 4; is the aim achieved?

int parent[6] = {-1, -1, -1, -1, -1, -1};
union1(0, 1);
union1(2, 3);
union1(1, 3);
union1(0, 4);
for (int i = 0; i < 6; i++)
  printf("%d ", find1(i));
Show answer

Output: 4 3 3 3 4 5

  • After the first three calls the links 0 → 1 → 3 and 2 → 3 exist: {0, 1, 2, 3} is a single set.
  • union1(0, 4) only writes parent[0] = 4. 0 is not a root; its link to 1 is lost and 0 alone moves under 4. The result is two sets: {1, 2, 3} and {0, 4}. The aim is not achieved.
012345parent403132-13-14-15

Roots must be passed: union1(find1(0), find1(4)); → parent[3] = 4, output 4 4 4 4 4 5.

Multiple Choice · Array Representation

Question 3: A Root Linked to Itself

5 and 7 are in the same set and the root of the set is 3. union1(3, 3) is called by mistake, followed by find1(5). What happens?

A: union1 writes parent[i] = j with no check: parent[3] = 3. The root is no longer negative, it points to itself. When find1(5) reaches 3, parent[3] >= 0 stays true forever and i = parent[i] gives 3 again: an infinite loop. That is why, before a union, the two roots found with find are checked to be different.

Multiple Choice · Analysis

Question 4: A Star-Shaped Union

Start with n singleton sets. union1(1, 0), union1(2, 0), …, union1(n−1, 0) are called, then find1(i) for every i. How many steps (i = parent[i]) are taken in total?

D: Every new element attaches directly to the root (0); the tree is a star with two levels. find1(0) takes no step, each of the other n − 1 calls takes one (7 for n = 8 in a program with a counter). With the chain-producing union1(i, i+1) the total is n(n − 1)/2. The number of unions is the same; the cost depends on which tree is attached to which.

Multiple Choice · Weighting Rule

Question 5: Argument Order

parent = [−2, 0, −4, 2, 2, 2] and union2(2, 0) is called. What does the array become?

B: p = −4 + (−2) = −6. parent[2] = −4 > parent[0] = −2 is false (set 2 has 4 vertices, set 0 has 2), so the else branch runs: parent[0] = 2, parent[2] = −6. union2(0, 2) gives the same array; the rule attaches the smaller tree to the larger one whatever the argument order. A attaches the larger to the smaller, C forgets to update the vertex count.

Step-by-Step Trace · Weighting Rule

Question 6: A Forest from Weighted Unions

n = 7, parent is all −1. union2(1,2), (3,1), (0,4), (1,0), (5,6), (5,1) are called in turn. What is the final array, and on which level is the deepest vertex?

0123456parent-10-11-12-13-14-15-16

Seven singleton sets; every root holds −1 (one vertex).

0123456parent-10-2112-13-14-15-16

union2(1, 2): −1 > −1 is false: of equal size, j attaches to i. parent[2] = 1, parent[1] = −2.

0123456parent-10-311213-14-15-16

union2(3, 1): −1 > −2 is true: 3's tree is smaller and attaches to 1. parent[1] = −3.

0123456parent-20-31121304-15-16

union2(0, 4): equal size: 4 attaches to 0. Two trees: 3 vertices at root 1, 2 at root 0.

0123456parent10-51121304-15-16

union2(1, 0): −3 > −2 is false: 0's tree (2 vertices) goes under 1. 4 is now on level 3.

0123456parent10-51121304-2556

union2(5, 6): equal size: 6 attaches to 5; parent[5] = −2.

0123456parent10-711213041556

union2(5, 1): −2 > −5 is true: 5's tree attaches to 1, parent[1] = −7. The deepest vertices (4 and 6) are on level 3: ⌊lg 7⌋ + 1 = 3.

void union2(int i, int j) {
  int p = parent[i] + parent[j];  /* -(size) */
  if (parent[i] > parent[j]) {    /* i smaller */
    parent[i] = j;
    parent[j] = p;
  } else {                  /* j not larger */
    parent[j] = i;
    parent[i] = p;
  }
}

Multiple Choice · Weighting Rule

Question 7: For Four Levels

A tree built only with union2 has 4 levels. What is the minimum number of vertices in the tree?

B: By the lemma the number of levels cannot exceed ⌊lg m⌋ + 1. 4 ≤ ⌊lg m⌋ + 1 gives ⌊lg m⌋ ≥ 3, that is m ≥ 8. A vertex's level grows only when its tree is attached to an equal or larger tree, and then the tree at least doubles: 1 → 2 → 4 → 8. Eight vertices, merging equal-sized trees pairwise, reach this bound.

Spot the Bug · Weighting Rule

Question 8: Reversed Comparison

This version of union2 has two bugs. With parent = [−2, 0, −1], what does the array become after union2(0, 2), and then what does find1(1) do? Fix the bugs.

void union2(int i, int j) {
  if (parent[i] < parent[j]) {   /* i smaller */
    parent[i] = j;
    parent[j] = parent[i] + parent[j];
  } else {
    parent[j] = i;
    parent[i] = parent[i] + parent[j];
  }
}
Show answer
  • −2 < −1 is true: the 2-vertex tree goes under the 1-vertex tree. A larger negative means fewer vertices; it must be >.
  • The sum uses the overwritten parent[0]: parent[2] = 2 + (−1) = 1. The array is [2, 0, 1]: no root at all.
021

Because of the cycle 1 → 0 → 2 → 1, find1(1) falls into an infinite loop. Fix: first p = parent[i] + parent[j], and compare with parent[i] > parent[j]. The correct version gives [−3, 0, 0].

Step-by-Step Trace · Collapsing Rule

Question 9: Collapsing on a Chain

parent = [−6, 0, 1, 2, 3, 0], find2(4) is called. How many rounds does each loop run and what does the array become?

012345parent-600112233405

Chain built with union1: 4 → 3 → 2 → 1 → 0. find2(4) is called.

012345parent-600112233405

parent[4] = 3 ≥ 0 → r = 3.

012345parent-600112233405

parent[3] = 2 ≥ 0 → r = 2.

012345parent-600112233405

parent[2] = 1 ≥ 0 → r = 1.

012345parent-600112233405

parent[1] = 0 ≥ 0 → r = 0. parent[0] = −6 < 0: the root is found (4 steps).

012345parent-600112230405

4 is attached directly to the root; i = s = 3.

012345parent-600112030405

3 is attached directly to the root; i = s = 2.

012345parent-600102030405

2 is attached directly to the root; i = s = 1.

012345parent-600102030405

parent[1] is already 0: one extra round; i = 0.

012345parent-600102030405

i == r: return 0. Every vertex on the path is now attached to the root; a second find2(4) takes a single step.

int find2(int i) {
  int r, s;
  for (r = i; parent[r] >= 0; r = parent[r])
    ;                 /* find the root */
  while (i != r) {    /* collapse path */
    s = parent[i];
    parent[i] = r;
    i = s;
  }
  return r;
}

Multiple Choice · Collapsing Rule

Question 10: Without Saving the Parent

Take a version with the variable s removed. parent = [−6, 0, 1, 2, 3, 0] and find2(4) is called. What happens?

int find2(int i) {
  int r;
  for (r = i; parent[r] >= 0; r = parent[r])
    ;
  while (i != r) {
    parent[i] = r;
    i = parent[i];
  }
  return r;
}

C: After parent[4] = 0 is written, i = parent[i] becomes 0, equal to r; the loop ends in the first round. The array is [−6, 0, 1, 2, 0, 0]: the root is found correctly; 3, 2 and 1 stay linked to their old parents (they are not cut) but their paths are not shortened. The parent must be saved before the link is changed.

Coding Question · Collapsing Rule

Question 11: Path Halving

find2 shortens the path in two passes. A collapse in a single pass can also be written: the vertex on the path is linked to its grandparent and we move on to that vertex (path halving). Write the routine int find_halving(int i). With parent = [−6, 0, 1, 2, 3, 0], what does the array become after find_halving(4)?

Show answer
int find_halving(int i) {
  while (parent[i] >= 0) {
    if (parent[parent[i]] >= 0)        /* has a grandparent */
      parent[i] = parent[parent[i]];
    i = parent[i];
  }
  return i;
}

i = 4: parent[4] = 2, i = 2. i = 2: parent[2] = 0, i = 0: root, returns 0. The array is [−6, 0, 0, 2, 2, 0].

012345parent-600102232405

The path of 4 shrank from 4 edges to 2; the skipped 3 keeps its link. One loop suffices, no extra variable.

Multiple Choice · Summary

Question 12: Only the Weighting Rule

The collapsing rule is not used: unions are done with union2, finds with find1. What is the worst-case total cost of n − 1 unions and m finds?

A: Each union is O(1): O(n) in total. Because the weighting rule bounds the depth by ⌊lg n⌋ + 1, every find is O(lg n): m finds cost O(m lg n). B is the bound of union1 without the rule (a chain); C is obtained only when the collapsing rule is added as well.

Output Question · Applications

Question 13: Connectivity Queries

parent[0..4] starts at −1; ops[k][0] = 1 means union, 0 means query. What does the program print, and what is parent at the end?

int ops[7][3] = {{1,0,1}, {1,2,3}, {0,1,3},
  {1,1,2}, {0,0,3}, {1,3,0}, {0,4,0}};
for (int k = 0; k < 7; k++) {
  int a = find2(ops[k][1]);
  int b = find2(ops[k][2]);
  if (ops[k][0] == 0)
    printf(a == b ? "Y " : "N ");
  else if (a != b)
    union2(a, b);
  else
    printf("redundant ");
}
Show answer

Output: N Y redundant N

  • (0,1) and (2,3) are united: parent = [−2, 0, −2, 2, −1]. Query (1,3): roots 0 and 2 → N.
  • Union (1,2): roots 0 and 2, equal size → 2 attaches to 0, parent[0] = −4.
  • Query (0,3): find2(3) finds the path 3 → 2 → 0 and attaches 3 to the root → Y.
  • Union (3,0): both have root 0 → redundant. Query (4,0): 4 is alone → N.

The final array is [−4, 0, 0, 0, −1]: {0, 1, 2, 3} and {4}. This is how online queries about network connectivity are answered.

Step-by-Step Trace · Applications

Question 14: The Edge That Closes a Cycle

The edges of an undirected graph are processed in order. What does find_cycle(5, 6, u, v) return?

01234parent-10-11-12-13-14

Edges in order: (0,1), (2,3), (1,3), (4,2), (0,2), (3,4). Every vertex is its own set.

01234parent-2001-12-13-14

(0,1): roots 0 and 1 differ → union2(0, 1).

01234parent-2001-2223-14

(2,3): roots 2 and 3 differ → union2(2, 3).

01234parent-40010223-14

(1,3): roots 0 and 2 differ → union2(0, 2).

01234parent-5001022304

(4,2): roots 4 and 0 differ → union2(4, 0).

01234parent-5001022304

(0,2): both ends have root 0. There is already a path between them (0 – 1 – 3 – 2); the edge closes a cycle: return 4.

int find_cycle(int n, int m, int u[], int v[]) {
  for (int i = 0; i < n; i++) parent[i] = -1;
  for (int e = 0; e < m; e++) {
    int a = find2(u[e]), b = find2(v[e]);
    if (a == b) return e;      /* cycle */
    union2(a, b);
  }
  return -1;                   /* forest */
}

Multiple Choice · Applications

Question 15: Unsupported Operation

Which of the following can a union-find structure built with a parent array, the weighting rule and the collapsing rule not do efficiently?

D: The structure only merges: it does not store which union brought which vertex, and the collapsing rule also changes the tree shape. When a network link is removed, the structure is rebuilt from scratch. A is done with two find calls, B with −parent[root] at the root, C with union2.

Coding Question · Summary

Question 16: The Largest Set

For a parent array built with union2, write int largest(const int parent[], int n, int *size), returning the root of the largest set and giving its size through the pointer. What is the result for parent = [3, −3, −5, 2, 2, 2, −1, 1, 1]?

Show answer
int largest(const int parent[], int n, int *size) {
  int root = -1, b = 0;
  for (int i = 0; i < n; i++)
    if (parent[i] < 0 && -parent[i] > b) {   /* root */
      b = -parent[i];
      root = i;
    }
  if (size != NULL) *size = b;
  return root;
}

Roots: 1 (3 elements), 2 (5) and 6 (1): returns 2, *size = 5.

Because the size is kept at the root, no find call is needed: one pass, O(n). const shows that the array is not modified, and the NULL check shows that the caller may not want the size.

The End

Chapter 16: Sets and Union-Find: Study Questions
Lecture slides: Chapter 16: Sets and Union-Find · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.