Search code examples
graphtime-complexityadjacency-listinsertion

Time Complexity of Adding Edge to Graph using Adjacency List


I've been studying up on graphs using the Adjacency List implementation, and I am reading that adding an edge is an O(1) operation.

This makes sense if you are just tacking an edge on to the Vertex's Linked List of edges, but I don't understand how this could be the case so long as you care about removing the old edge if one already exists. Finding that edge would take O(V) time.

If you don't do this, and you add an edge that already exists, you would have duplicate entries for that edge, which means they could have different weights, etc.

Can anyone explain what I seem to be missing? Thanks!


Solution

  • You're right at your complecxity analysis. Find if edge already exist is truly O(V). But notice that adding this edge even if existed is still O(1).

    You need to remember that having 2 edges with the same source an destination are valid input to graph - even with different weights (maybe not even but because).

    That way adding edge to adjacency-list-graph is O(1)