1. Repeated Array Scan for Zero In-Degree
Intuition
Maintain in-degree array. In each of V rounds, scan all vertices linearly to find an unprocessed node with in-degree 0.
Algorithm
- Compute in-degree array of size V.
- Create visited array of size V initialized to false.
- Repeat V times:
- Scan for unvisited node u with inDegree[u] == 0.
- If no such node exists: cycle detected, return [].
- Mark visited[u] = true, append u to result.
- For each neighbor v of u: inDegree[v]--.
- Return result.
#include <iostream>#include <vector> using namespace std; vector<int> kahnsLinearScan(int V, const vector<vector<int>>& adj) { vector<int> inDegree(V, 0); for (int u = 0; u < V; ++u) { for (int v : adj[u]) inDegree[v]++; } vector<bool> visited(V, false); vector<int> result; for (int step = 0; step < V; ++step) { int u = -1; for (int i = 0; i < V; ++i) { if (!visited[i] && inDegree[i] == 0) { u = i; break; } } if (u == -1) return {}; // Cycle detected visited[u] = true; result.push_back(u); for (int v : adj[u]) { inDegree[v]--; } } return result;} int main() { int V = 6; vector<vector<int>> adj = {{}, {}, {3}, {1}, {0, 1}, {0, 2}}; auto res = kahnsLinearScan(V, adj); cout << "Topological Sort (Linear Scan): "; for (int v : res) cout << v << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(V^2 + E) - Space complexity:
O(V)