Data Structure to Design a special social network
Consider a special social network where people are called connected if one person is connected to other with any number of intermediate connections. For example if a person x is connected with y and y is connected with z, then x is also considered to be connected with z. We are given a set of friend requests as input. We are also given a set of queries where each query has input pair i and j. For each query, we need to tell whether i and j are connected or not. Examples:
Input : Connections : connect(0, 1), connect(1, 2), connect(0, 3), connect(5, 6), connect (0, 7) areConnected(2, 7) areConnected(2, 6) areConnected(1, 7) Output : Yes No Yes Explanation : Note that 0 is connected to 2 and 0 is also connected to 7. Therefore 2 and 7 are considered as connected. Input : Connections : connect(0, 2), connect(4, 2), connect(1, 3) areConnected(0, 4) areConnected(0, 1) Output : Yes No
The idea is to use disjoint set data structure. With this data structure, we can solve all queries in O(1) amortized time.