0

I know that time complexity of shortest path via BFS is O(V+E). But I have found one of algorithm's implementations on Python which looks like this.

def search(name):
   search_queue = deque()
   search_queue += graph[name]  # graph is a dict<string: list of strings>

   searched = []
   while search_queue:
      person = search_queue.popleft()
      if person not in searched:
         if some_checking(person):
            return True
         else:
            search_queue += graph[person]
            searched.append(person)

   return False

In the outer loop we traverse through each vertex in the graph and each iteration we check whether the vertex has been already visited. Searching will take O(N) operations since searched is a list. Am I right that time complexity is O(V^2) in this implementation?

1 Answers1

2

Yes, you are correct. Searching if the node was already visited can take up to O(V) and it is done O(V) times. This code is O(V^2).

It can be easily improved by changing the data structure used to store visited nodes. Changing from list to set, will make this code works in O(V + E).

Marcelo Fornet
  • 548
  • 3
  • 12
  • Thank you so much! One more question, just to make sure, `O(V)` means that we go through each vertex and `O(E)` means how many appends to `search_queue` will be performed, am I right? – learnermissed Jul 01 '21 at 15:39
  • For `O(V)` you are correct, for `O(E)` it means the algorithm also depends linearly on the number of edges. In this case it is noted in the line `search_queue += graph[person]`. The cost of this line is proportional to the number of neighbors, but the sum of all neighbors it less than 2 * E. – Marcelo Fornet Jul 01 '21 at 15:45
  • Yea, by the phrase _how many appends to search_queue_ I mean exactly the line `search_queue += graph[person]`. The last words `O(2 * E)` is about undirected graphs? Because for directed graph it will be exactly `O(E)`. P.S. Sorry for such primitive questions, I just try to make it clear. – learnermissed Jul 01 '21 at 16:00
  • Thanks! Really appreciate it. – learnermissed Jul 01 '21 at 18:18