# Topological Sort

![](/files/gQu9xtXo10lr3Mima35R)

* j + d, j +d
* v +e, v+e

```jsx
function topologicalSort(jobs, deps) {
  const answer = [];
  // create adj list for each job
  const adj = {};
  for (let i = 0; i < jobs.length; i++) {
    const job = jobs[i];
    if (adj[job] === undefined) 
      adj[job] = [];
  }
  
  // form a adj list
  // count edges directing there
  const inCommingEdges = {};
  for (let i = 0; i < deps.length; i++) {
    const [here, there] = deps[i];
    adj[here].push(there);
    
    if (inCommingEdges[there] === undefined) 
      inCommingEdges[there] = 0;
    inCommingEdges[there] += 1;
  }

  // pick all edges, which has no incomming edges
  const q = [];
  for (const [here, edges] of Object.entries(adj)) {
    if (inCommingEdges[here] > 0) continue;
    q.push(here);
  }

  // use bfs to search toplogical sort
  while (q.length > 0) {
    const here = q.shift();
    for (const there of adj[here]) {
      inCommingEdges[there]--;
      if (inCommingEdges[there] > 0) continue;
      q.push(there);
    }
    answer.push(here);
  }

  console.log({
    answer
  });
  
  return answer.length === jobs.length ? answer : [];
}

// not working with dfs
// function dfs(adj, visited, here, order) {
//   visited[here] = 1;
  
//   for (let i = 0; i < adj[here].length; i++) {
//     const there = adj[here][i];
//     if (visited[there] !== 0) continue;

//     // if (visited[there] === 1) continue;
//     dfs(adj, visited, there, order);
//   }
  
//   visited[here] = 2;
// }
// Do not edit the line below.
exports.topologicalSort = topologicalSort;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/algoexpert/hard/topological-sort.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
