For a homework problem I was asked the question of given a set of n nodes and m edges where the graph was represented by an adjacency list, why insertVertex would take O(1) and deleteVertex would take O(m).
I’m not entirely sure of my answer, but I put that insertVertex is O(1) because when you first insert, all you add to the array is one node and a set of adjacent vertices (meaning vertices that your new node points to). Thus this time complexity is constant. However, when you remove a node, not only do you have to remove the node and the adjacent edges that come with the node, you also have to go through the rest of the m edges to make sure that you remove the ones that point to the node that you are trying to remove (since you can’t have an edge that points to nothing.
I’m new to graph theory so I don’t know if my way of thinking is correct.
The O(m) explanation is right.
Your explanation would be better if you explained the actions in terms of linked list manipulations. It takes O(1) time to append a node to a linked list. And it takes O(n) time to delete an item.
a) Why insertVertex is O(1)?
Inserting a vertex is just appending a node to a linked list (O(1)) or 2 if the graph is undirected.
b) Why deleteVertex is O(m)?
Deleting a vertex means:
1) Delete a linked list (O(1))
2) In the worst case you will have to remove the vertex from all the linked lists: O(m). It’s O(m) cause the number of nodes in all the linked lists is m, or 2*m if the graph is undirected.