I’m creating an algorithm that can build an adjacency list from a list of edges.
For example, if the data input was:
1 2
1 8
2 8
3 5
3 1
4 5
4 6
5 2
5 9
6 4
6 8
7 4
7 10
8 4
8 6
9 4
9 5
10 7
10 3
The output would be:
1: 8 4 6
2: 4 6
3: 9 2 8
4: 2 9 8
5: 8 4
6: 5 4
7: 5 6 3
8: 5 6 4
9: 5 6 2
10: 4 5 1
The algorithm is obviously bounded by the number of vertices and edges so originally I was thinking it would be O(v + e). But I could only get the program to work by implementing for loops inside for loops with 2d arrays, which I believe cause complexity of O(N^2).
Can anyone help me better understand?
It depends a fair bit on what sort of data structure you are using to store the map from vertices to lists of adjacent vertices. Iterating through the list of edges is of course going to have time complexity O(e). Any larger time complexity is going come from the time required to find a vertex in the map and the time required to insert a new item into a vertex’s list of adjacent vertices. If you were using flat arrays then you could have O(v*e) complexity (for each edge, loop through the vertex list to find the desired vertex), but this could be improved quite a lot by using a hash-table or tree data structure that gave you better lookup performance.