# PRINCETON Course Algorithms Interview Questions: Union Find

Coursera上不仅有课后作业，还有面试题目，下面分析一下所给题目。

const int N = 111111;

int id[N];

void Init()
{
for (int i = 0; i < N; ++i) {
id[i] = i;
}
}

int Find(int p)
{
if (id[p] == p) return id[p];
else {
return id[p] = Find(id[p]); // compress the path
}
}

bool Connected(int p, int q)
{
return Find(p) == Find(q);
}

void Union(int p, int q)
{
int i = Find(p);
int j = Find(q);
id[i] = j;
}


## Reference

Coursera Algorithms Part1 Union-Find Interview Question
https://class.coursera.org/algs4partI-009/quiz/attempt?quiz_id=89

## Question 1

Social network connectivity. Given a social network containing N members and a log file containing M timestamps at which times pairs of members formed friendships, design an algorithm to determine the earliest time at which all members are connected (i.e., every member is a friend of a friend of a friend … of a friend). Assume that the log file is sorted by timestamp and that friendship is an equivalence relation. The running time of your algorithm should be MlogN or better and use extra space proportional to N.

## Question 2

Union-find with specific canonical element. Add a method find() to the union-find data type so that find(i) returns the largest element in the connected component containing i. The operations, union(), connected(), and find() should all take logarithmic time or better.
For example, if one of the connected components is {1,2,6,9}, then the find() method should return 9 for each of the four elements in the connected components because 9 is larger 1, 2, and 6.

## Question 3

Successor with delete. Given a set of N integers S={0,1,…,N−1} and a sequence of requests of the following form:

• Remove x from S
• Find the successor of x: the smallest y in S such that y≥x.
design a data type so that all operations (except construction) should take logarithmic time or better.

find只需返回根节点的值。

## Question 4

Union-by-size. Develop a union-find implementation that uses the same basic strategy as weighted quick-union but keeps track of tree height and always links the shorter tree to the taller one. Prove a lgN upper bound on the height of the trees for N sites with your algorithm.

### Solution

SHARE · JOBHUNTING
Algorithm Interview Questions Coursera