![]() |
VOOZH | about |
Given two integers N and K, where N denotes the number of vertices in a Graph. There is an edge between two vertices u and v if there exists some z > K: u % z ==0: v % z ==0. Now you have to answer Q queries of the form [ i, j ] where you have to print whether i and j are connected (i.e. there is some path between i and j ) or not.
Examples:
Input: N=6, K=2, queries: [[1, 4],[2, 5],[3, 6]]
Output: false false true
Explanation:
In the query [1, 4] there is no connection, between vertex 1 and vertex 4 in the graph so the result is "false."
Likewise in the query [2, 5] there is no link between vertex 2 and vertex 5 in the graph resulting in "false" again.
However with regards to the query [3, 6] a path does exist between vertex 3 and vertex 6 in the graph leading to a result of "true."Input: N = 8, K = 3, queries = [[1, 5], [2, 7], [4, 8], [3, 6]]
Output: false false true false
Explanation:
In the query [1, 5] there is no path connecting vertex 1 and vertex 5 in the graph; thus it yields a result of "false."
for the query [2,7] there is no connection between vertex 2 and vertex 7 in the graph; henceforth producing a result of "false."
Additionally, when considering the query [4,8] there is a path linking vertex 4 and vertex 8 within the graph. As a result, "true" is returned.
However, the fourth query[3,6] reveals no path connecting vertex three and six, within this graph. Therefore the outcome will be evaluated as"false."
Approach: To solve the problem follow the below idea:
The main idea is to utilize the Union Find (Disjoint Set Union) data structure, for creating and handling the connections in the graph. By going through values of z from K+1 to N and linking vertices that satisfy the given conditions the algorithm constructs the graph. Then for each inquiry it verifies if two vertices belong to the group by locating their root parents using path compression, in the Union Find operations.
The following steps are required to solve this problem:
Below is the implementation for the above approach:
false false true false false true false
Time Complexity: O(N + Q) where N is the number of elements, and Q is the number of queries.
Auxiliary Space: O(N)