As per my understanding, both DFS and BFS take O(V+E). But is it possible for the search algorithms to have different time complexities?
For example, in this problem (https://leetcode.com/problems/kill-process/#/description) using DFS takes longer than BFS.
BFS:
class Solution(object):
def bfs(self, pid, ppid, tmp, output):
child = []
for i in xrange(len(ppid)):
if ppid[i] in tmp:
output.append(pid[i])
child.append(pid[i])
if child != []:
self.bfs(pid, ppid, child, output)
def killProcess(self, pid, ppid, kill):
"""
:type pid: List[int]
:type ppid: List[int]
:type kill: int
:rtype: List[int]
"""
output, tmp = [kill], [kill]
self.bfs(pid, ppid, tmp, output)
return output
Time complexity: O(NlgN)
DFS:
class Solution(object):
def dfs(self, pid, ppid, kill, output):
for i in xrange(len(ppid)):
if ppid[i] == kill:
if kill not in output:
output.append(kill)
self.dfs(pid, ppid, pid[i], output)
if kill not in output:
output.append(kill)
def killProcess(self, pid, ppid, kill):
"""
:type pid: List[int]
:type ppid: List[int]
:type kill: int
:rtype: List[int]
"""
output = []
self.dfs(pid, ppid, kill, output)
return output
Time complexity: O(N^2)
ppid? I see you're passing-inppidin each recursive call which is then iterated-over on each node visit - that's inefficient and not inherent in any DFS algorithm implementation.ppidis a list. Btw, since I dont go over the same path again (eventhoughppidis iterated over and over again at each recursive call), isnt this still DFS?ppidlist, hence theO(n^2)runtime complexity. Your use of thein outputoperator will also iterate overoutputinO(n)time (I believe - I'm not too well-versed in Python) - you should use a hashset or hashmap (associative-array, dictionary) type forO(1)lookup instead.inoperator takes justO(1)as python maintains an internal hashmap for each lists. Btw, I now get it where I'm going wrong: Theppidandpidlists has a tree structure so there is no need to have an additional "visited" node list. However, at each run the code iterates over the entire tree (ppid) to check for a particular node (pid) rather than parsing just a particular subtree. Thanks! Now, I'm curious how my BFS implementation takes just O(NlgN). I would be grateful if you could correct me incase I'm wrong with the time complexity calculation!