I am unable to comprehend how the time complexity of the BFS of a graph is O(v+2E), where V is the number of vertices and E being the number of edges.
/**
* @param {number} V
* @param {number[][]} adj
* @returns {number[]}
*/
class Solution {
// Function to return Breadth First Traversal of given graph.
bfsOfGraph(V, adj) {
const queue=new Queue();
const visited=Array.from({length:V},()=>false);
const ans=[];
queue.add(0);
visited[0]=true;
while(!queue.isEmpty()){
const el=queue.remove();
ans.push(el);
for(const v of adj[el]){
if(!visited[v]){
queue.add(v);
visited[v]=true;
}
}
}
return ans;
}
}
class Queue {
constructor() {
this.arr = [];
this.start = 0;
this.end = -1;
}
add(el) {
this.arr.push(el);
this.end++;
}
remove() {
if (this.isEmpty())
return;
let el = this.arr[this.start];
this.start++;
return el;
}
isEmpty() {
return this.start > this.end;
}
get length() {
return this.end - this.start < 0 ? 0 : this.end - this.start + 1;
}
}
In the above javascript implementation of the BFS of a graph, since the queue only holds the vertices that haven't been visited which makes the outer loop run for exactly V times and for each vertex, we check if it's neigbouring nodes have been visited by looking at the visited array, which in itself is an O(1) operation. So, technically for each vertex we make O(1) operations equal to the degree of that vertex. So, why isn't the TC of the algorithm equal to O(V*avg. degree of a graph).
I tried everything but still don't have a clue. I checked a similar question on stack overflow but it didn't help. Can someone explain me why it's O(V+E) instead of O(V*avg. degree of graph).