Master programming syntax, solve interactive challenges & run live code in Syntaxis Explore Arena →
menu_book Course Curriculum (Data Structures & Algorithms) expand_more
Complexity & Foundations
Arrays & Strings
Linked Lists
Stacks & Queues
Hashing
Trees & Heaps
Graphs
Sorting Searching & DP

Topological sort

Learn Topological sort in Data Structures & Algorithms with a focused explanation, a topic-specific example, edge guidance, and a mastery check.

12 min read • Advanced
data-structures-algorithms-067.py
python
from collections import deque
g={"A":["C"],"B":["C"],"C":["D"],"D":[]};ind={n:0 for n in g}
for vs in g.values():
    for v in vs:ind[v]+=1
q=deque(n for n,d in ind.items() if d==0);order=[]
while q:
    n=q.popleft();order.append(n)
    for v in g[n]:
        ind[v]-=1
        if ind[v]==0:q.append(v)
print(order)
What to watch
Content source & attribution
Original Syntaxis Content · Original Syntaxis Content