I agree with you @Gaurav7, it needs the graph formation so it ends with the same space complexity. I used the same approach so here is the full code, in case anybody is interested:
from collections import deque
def topological_sort(vertices, edges):
incoming = [0 for _ in range(vertices)]
outgoing = [[] for _ in range(vertices)]
for p, c in edges:
incoming[c] += 1
outgoing[p] += [c]
sources = deque()
for i in range(vertices):
if incoming[i] == 0:
sources.append(i)
order = []
while sources:
v = sources.popleft()
order.append(v)
for e in outgoing[v]:
incoming[e] -= 1
if incoming[e] == 0:
sources.append(e)
if len(order) != vertices:
return []
return order