Blog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2025 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Algorithms
Algorithmshard

What is a topological sort and when is it possible?

Tags
#topological-sort#dag#graph
Back to categoryPractice quiz

Answer

It orders vertices so every directed edge u→v goes from earlier to later. It exists only for a DAG (directed acyclic graph); any cycle means no valid topological order.

function topoSort(n: number, edges: Array<[number, number]>) {
  const indeg = Array(n).fill(0);
  const g: number[][] = Array.from({ length: n }, () => []);

  for (const [u, v] of edges) {
    g[u].push(v);
    indeg[v]++;
  }

  const q: number[] = [];
  for (let i = 0; i < n; i++) if (indeg[i] === 0) q.push(i);

  const order: number[] = [];
  while (q.length) {
    const u = q.shift()!;
    order.push(u);
    for (const v of g[u]) {
      indeg[v]--;
      if (indeg[v] === 0) q.push(v);
    }
  }

  return order.length === n ? order : null; // null => cycle
}

Related questions

Algorithms
When can BFS replace Dijkstra’s algorithm?
#shortest-path#bfs#dijkstra
Algorithms
BFS vs DFS — what’s the difference and when to use which?
#bfs#dfs#graph
Algorithms
What is Dijkstra's Algorithm?
#graph#shortest-path
#dijkstra
Algorithms
BFS vs DFS?
#graph#bfs#dfs
Data Structures
Adjacency list vs adjacency matrix: when do you choose each?
#graph#adjacency-list#adjacency-matrix