VOOZH about

URL: https://www.geeksforgeeks.org/dsa/island-connectivity-for-q-queries/

⇱ Island Connectivity for Q queries - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Island Connectivity for Q queries

Last Updated : 23 Jul, 2025

Given an integer N denoting the number of disconnected islands from 1 to N. You have to process Q queries of the following types:

  • Type 1 query: 0 u v => Connect islands u and v
  • Type 2 query: 1 u v => Print "YES" if islands u and v are connected otherwise print "NO"

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:

  • Construct the Union() and Find() functions of DSU.
  • Initialize the Parent[] array for each island 'i' such that parent[i]=i.
  • Now process each query one by one as per below condition
    • If Type 1 query: Union(island u, island v)
    • If Type 2 query: Print Yes if Find(island u) == Find(island v), otherwise print NO.

Below is the code for the above approach:


Output
Yes
No
Yes
Yes
No

Complexity Analysis:

  • Time Complexity: max(N, Q) where N is the number of Islands and Q is total number of queries
  • Auxiliary Space: O(N) for the parent array
Comment
Article Tags: