![]() |
VOOZH | about |
Given an integer N denoting the number of disconnected islands from 1 to N. You have to process Q queries of the following types:
Note: The connection between the islands follows transitive property.
Examples:
Input: N = 5, Q = 8, Queries = [[0 1 2], [1 2 1], [0 3 4], [1 1 4], [0 3 2], [1 2 3], [1 1 4], [1 1 5]]
Output: [YES, NO, YES, YES, NO]
Explanation: Initially islands = {1}, {2}, {3}, {4}, {5}
- query[0] island '1' and island '2' merge => {1, 2}, {3}, {4}, {5}
- query[1] => print YES as island 2 and island 1 is connected
- query[2] island '3' and island '4' merge => {1, 2}, {3, 4}, {5}
- query[3] => print NO as island 1 and island 4 are not connected.
- query[4] island '3' and island '2' merge => {1, 2, 3, 4}, {5}
- query[5] => print YES as island 2 and island 3 are connected.
- query[6] => print YES as island 1 and island 4 are connected.
- query[7] => print NO as island 1 and island 5 are not connected.
Input: N = 3, Q = 3, Queries = [[1 1 2], [1 2 3], [1 1 3]]
Output: [NO, NO, NO]
Explanation: Clearly there is no query of Type 1, hence all the islands remain disconnected.
Approach: We can solve this problem using the Disjoint Set Union (DSU) data structure:
Observations:
If we break down this question to a smaller scale, we observe that for each Type 1 query we have to put two disjoint island into a same set and for each query of Type 2 we have to know whether the two island belong to same set or are disjoint to each other. What data structure can be used to tackle this situation?
YES you guessed it right, this problem revolves around the construction of a Union and find functions of DSU.
- For Type 1 query: Use Union() operation of DSU to Merge the two disjoint islands u and v.
- For Type 2 query: Use Find() function to know whether the two island u and v have same parent or not.
Follow the steps to solve the problem:
Below is the code for the above approach:
Yes No Yes Yes No