Topological Sort Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Topological Sort runs in O(V+E) time and O(V) space, in Go as in every other language.
- ✓container/heap is the real stdlib priority-queue tool, but it is an interface you implement (Len, Less, Swap, Push, Pop) rather than a ready-made generic type, there is no equivalent of Python's heapq-on-a-plain-list.
- ✓Pre-size the queue slice with make([]T, 0, len(nodes)) to avoid the geometric-growth reallocations a growing slice otherwise pays, and pop via a head index (queue[head]; head++) rather than re-slicing the front off with queue = queue[1:], the two look equivalent but only one of them is memory-neutral (see pitfall).
- ✓The Go trap: Re-slicing from the front with queue = queue[1:] does not free the element you dropped: a Go slice is a (pointer, length, capacity) triple into a single backing array, so as long as any live slice still points into that array, the whole array, including the elements before your current window, stays reachable and the garbage collector cannot reclaim it.
- ✓O(V+E) with the head-index slice approach, since both append (amortized) and the indexed read are O(1).
What Topological Sort actually is
Topological Sort in Go: what you actually reach for
Go implementation
package graph
import "errors"
func topoOrder(adj map[string][]string) ([]string, error) {
indegree := make(map[string]int, len(adj))
for node := range adj {
if _, ok := indegree[node]; !ok {
indegree[node] = 0
}
for _, next := range adj[node] {
indegree[next]++
}
}
queue := make([]string, 0, len(indegree)) // pre-sized, popped via head index, never queue[1:]
for node, d := range indegree {
if d == 0 {
queue = append(queue, node)
}
}
order := make([]string, 0, len(indegree))
head := 0
for head < len(queue) {
node := queue[head]
head++
order = append(order, node)
for _, next := range adj[node] {
indegree[next]--
if indegree[next] == 0 {
queue = append(queue, next)
}
}
}
if len(order) != len(indegree) {
return nil, errors.New("not a DAG: cycle present")
}
return order, nil
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(V+E)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Topological Sort?
container/heap is the real stdlib priority-queue tool, but it is an interface you implement (Len, Less, Swap, Push, Pop) rather than a ready-made generic type, there is no equivalent of Python's heapq-on-a-plain-list. For the plain FIFO version there is no dedicated queue type either; the idiomatic choice is a slice plus a head index, or container/list for a real doubly-linked list when you need O(1) removal from arbitrary positions.
What is the most common Go mistake when implementing Topological Sort?
Re-slicing from the front with queue = queue[1:] does not free the element you dropped: a Go slice is a (pointer, length, capacity) triple into a single backing array, so as long as any live slice still points into that array, the whole array, including the elements before your current window, stays reachable and the garbage collector cannot reclaim it. In a long-running service that keeps re-slicing a queue that grows and shrinks repeatedly, this silently retains memory proportional to the largest the queue ever grew, not its current size.
How does Topological Sort actually perform in Go?
O(V+E) with the head-index slice approach, since both append (amortized) and the indexed read are O(1). container/heap's Push and Pop are O(log n) through its interface dispatch, which, because the interface methods are not inlined the way a monomorphic generic function would be, carries a real per-call indirection cost on top of the logarithmic factor, worth measuring before assuming a hand-rolled slice-based heap would not be faster for a known concrete type. Time complexity is O(V+E) and space is O(V).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.