Union and Intersection of two Graphs

• Difficulty Level : Easy
• Last Updated : 21 Apr, 2021

Given two graphs G1 and G2, the task is to find the union and intersection of the two given graphs, i.e. (G1 ∪ G2) and (G1 ∩ G2).

Examples:

Input: G1 = { (“e1”, 1, 2), (“e2”, 1, 3), (“e3”, 3, 4), (“e4”, 2, 4) }, G2 =  = { (“e4”, 2, 4), (“e5”, 2, 5), (“e6”, 4, 5) }
Output:
G1 union G2 is
e1 1 2
e2 1 3
e3 3 4
e4 2 4
e5 2 5
e6 4 5

G1 intersection G2 is
e4 2 4
Explanation:
Union of the graphs G1 and G2: Intersection of the graphs G1 and G2: Approach: Follow the steps below to solve the problem:

• Define a function, say Union(G1, G2), to find the union of the G1 and G2:
• Initialize a map, say added, that stores if an edge is already been added or not.
• Iterate over the edges of the graph G1 and push all the edges in a graph, say G, and mark all the edges visited in added.
• Now, again traverse over the edges of the graph G2 and push the edge in the G if the edge is not already been added, and then mark the edge added in the map added.
• Define a function say Intersection(G1, G2) to find the Intersection of the G1 and G2:
• Initialize a map, say added , that stores if an edge is already been added or not.
• Traverse over the edges of the graph G1 and marked all the edges visited in the map added.
• Now, again traverse over the edges of the graph G2 and push the edge in the graph G, if the edge is already been added. Then, mark the edge added in the map.
• Now, print the graphs obtained after the function call of Union(G1, G2) and Intersection(G1, G2).

Below is the implementation of the above approach:

C++14

Output:
G1 union G2 is
e1 1 2
e2 1 3
e3 3 4
e4 2 4
e5 2 5
e6 4 5
G1 intersection G2 is
e4 2 4

Time Complexity: O(N * log(N))
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up