> For the complete documentation index, see [llms.txt](https://coding-9.gitbook.io/untitled/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://coding-9.gitbook.io/untitled/graph/topo-sort/topological-sort.md).

# Topological sort

## Problem Statement

\
Given a Directed Acyclic Graph (DAG) with V vertices and E edges, Find any Topological Sorting of that Graph.

**Example 1:**

<pre><code><strong>Input:
</strong>
<strong>Output:
</strong>1
<strong>Explanation:
</strong>The output 1 denotes that the order is
valid. So, if you have, implemented
your function correctly, then output
would be 1 for all test cases.
One possible Topological order for the
graph is 3, 2, 1, 0.
</code></pre>

**Example 2:**

<pre><code><strong>Input:
</strong>
<strong>Output:
</strong>1
<strong>Explanation:
</strong>The output 1 denotes that the order is
valid. So, if you have, implemented
your function correctly, then output
would be 1 for all test cases.
One possible Topological order for the
graph is 5, 4, 2, 1, 3, 0.
</code></pre>

**Your Task:**\
You don't need to read input or print anything. Your task is to complete the function **topoSort()**  which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns an array consisting of the vertices in Topological order. As there are multiple Topological orders possible, you may return any of them. If your returned topo sort is correct then the console output will be 1 else 0.

**Expected Time Complexity:** O(V + E).\
**Expected Auxiliary Space:** O(V).

**Constraints:**\
2 ≤ V ≤ 104\
1 ≤ E ≤ (N\*(N-1))/2

## Intuition

```
Approach 1:

DFS traversal, till end 
add end elements to stack, So on, Goes second last etc, till start

Approach 2:
Kahn Alg

Track indegree of each node, Start from each node with 0 indegree the start
points and push them, remove indeg of all its chlidren, If child indeg becomes
zero do for them


```

### Links

### Video Links

### Approach 1:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
class Solution
{
public:
    void dfs(int node, vector<bool> &visited, stack<int> &s, vector<int> adj[]){
        visited[node] = true;
        
        for(auto &it: adj[node]){
            if(!visited[it]){
                dfs(it, visited, s, adj);
            }
        }
        s.push(node);
    }

	vector<int> topoSort(int V, vector<int> adj[]) 
	{
	    vector<bool> visited(V,false);
	    stack<int> s;
	    vector<int> ans;
	    
	    for(int i=0; i<V; i++)
	        if(!visited[i])
	            dfs(i,visited,s,adj);
	    
	    while(!s.empty()){
	        ans.push_back(s.top());
	        s.pop();
	    }
	    return ans;
	}
};
```

{% endcode %}

### Approach 2:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
class Solution
{
public:
    vector<int> topoSort(int V, vector<int> adj[]) {
        vector<int> indeg(V,0);
        queue<int> q;
        // Put all the indegree values by using this loop
        for(int i=0; i<V; i++)
            for(auto &it: adj[i])
                indeg[it]++;
                
        // Start with nodes not having any degree as they are coming first
        for(int i=0; i<V; i++)
            if(indeg[i] == 0)
                q.push(i);
                
        vector<int> ans;
        // Take one by one element and remove the degree of the children        
        while(!q.empty()){
            int temp = q.front();
            
            for(auto &it: adj[temp]){
                indeg[it]--;
                if(indeg[it] == 0)
                    q.push(it);
            }
            ans.push_back(temp);
            q.pop();
        }
        return ans;
    }
};
```

{% endcode %}

### Approach 3:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 4:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Similar Problems

###


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://coding-9.gitbook.io/untitled/graph/topo-sort/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.
