734 views
2 2 votes
What will be complexity to reverse the directed graph?(By reverse i mean reverse direction of all edges).Assume graph is represented by adjacency list.

i) No extra space

ii)May use extra space

1 Answer

1 1 vote

$O(|V| + |E|)$

Consider this Directed Graph,

Now, adjacency list for this graph will be

V1 => V2

V2 => V3

V3 => V1

Create new empty list for all Nodes.

Key statement, 

V2 is present in V1's list means V1 to V2 we have directed edge. To make it reverse i.e. V2 to V1 directed edge, add V1 into V2's list(newly created list). follow this procedure for all nodes.

V2 => V3 means V2 to V3 we have directed edge so to reverse it, add V2 to V3's list(newly created list).

That's how we have reversed list in the end that is nothing but reversed directed edges.

New list for above graph will look like,

V1 => V3

V2 => V1

V3 => V2.

more explanation,

A => B | C | D is list that means we have directed edge from A to B, C, D. Now to make it reverse, add A to B, C and D's list(new list).

the list will look like,

B => A,

C => A, 

D => A.

Position:
Show:

Related questions

7 7 votes
2 2 answers
236
236 views
GO Classes asked Jul 6
236 views
The following function is supposed to reverse a singly linked list:struct node { int data; struct node *next; }; static void reverse(struct node head_ref) { struct node ...
2 2 votes
1 1 answer
1.3k
1.3k views
Souvik33 asked Jan 11, 2023
1,261 views
The following C function rearranges the members of a single-linked list of integers that is passed as a parameter. The list of numbers 1, 2, 3, 4, 5, 6, and 7 in the spec...
1 1 vote
0 0 answers
1.7k
1.7k views
1 1 vote
2 answers 2 answers
1.3k
1.3k views
Souvik33 asked Nov 28, 2022
1,296 views
MSQ Consider the following C snippet:#include <stdio.h int main() { int *ptr = (int*) malloc(100*sizeof(int)); *ptr=33; printf("%d %d\n",ptr,*ptr); // Line X free(ptr); *...