Topological Sort Implementation in Swift
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 Swift as in every other language.
- ✓Foundation and the standard library have no built-in Deque; the real, Apple-maintained answer is the separate swift-collections package (import Collections), whose Deque<T> gives O(1) popFirst() and append() backed by a ring buffer, unlike Array's removeFirst().
- ✓Reach for swift-collections' Deque<T> once the graph is large enough that O(n) removeFirst() calls would matter, and say so explicitly in review when you deliberately choose plain Array.removeFirst() for a small, bounded input instead, that is a legitimate tradeoff (one fewer external dependency) but only when it is a stated choice, not an oversight.
- ✓The Swift trap: Array.removeFirst() is O(n): Array's storage is a single contiguous buffer, so removing the first element requires shifting every remaining element down by one, unlike Rust's VecDeque or Python's collections.deque, the Swift standard library has no ring-buffer-backed sequence type built in, so the naive, obvious implementation (just use an Array as a queue) silently degrades Kahn's algorithm from O(V+E) to O(V^2) exactly like the Python-list and JavaScript-.shift() traps, and the fix requires reaching for a package that is not part of the standard library.
- ✓O(V+E) once you are using Deque<T>'s O(1) popFirst() and append(); with plain Array.removeFirst() it is O(V^2) as above.
What Topological Sort actually is
Topological Sort in Swift: what you actually reach for
Swift implementation
import Collections // swift-collections: the ecosystem Deque, not in the standard library
enum TopoError: Error { case cyclePresent }
func topoOrder(_ graph: [String: [String]]) throws -> [String] {
var indegree: [String: Int] = [:]
for node in graph.keys { indegree[node, default: 0] += 0 }
for (_, nexts) in graph {
for next in nexts { indegree[next, default: 0] += 1 }
}
var queue: Deque<String> = Deque(indegree.filter { $0.value == 0 }.map { $0.key })
var order: [String] = []
order.reserveCapacity(indegree.count)
while let node = queue.popFirst() { // O(1): Array.removeFirst() would be O(n) here
order.append(node)
for next in graph[node] ?? [] {
indegree[next]! -= 1
if indegree[next] == 0 {
queue.append(next)
}
}
}
guard order.count == indegree.count else {
throw TopoError.cyclePresent
}
return order
}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 Swift-specific trap
Performance in Swift, beyond the O(V+E)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Topological Sort?
Foundation and the standard library have no built-in Deque; the real, Apple-maintained answer is the separate swift-collections package (import Collections), whose Deque<T> gives O(1) popFirst() and append() backed by a ring buffer, unlike Array's removeFirst().
What is the most common Swift mistake when implementing Topological Sort?
Array.removeFirst() is O(n): Array's storage is a single contiguous buffer, so removing the first element requires shifting every remaining element down by one, unlike Rust's VecDeque or Python's collections.deque, the Swift standard library has no ring-buffer-backed sequence type built in, so the naive, obvious implementation (just use an Array as a queue) silently degrades Kahn's algorithm from O(V+E) to O(V^2) exactly like the Python-list and JavaScript-.shift() traps, and the fix requires reaching for a package that is not part of the standard library.
How does Topological Sort actually perform in Swift?
O(V+E) once you are using Deque<T>'s O(1) popFirst() and append(); with plain Array.removeFirst() it is O(V^2) as above. Deque<T> is itself a value type with copy-on-write like Array, so the same rule from cycle detection applies: passing it around read-only is free, but holding two live references to it while mutating one triggers a real, silent full copy. 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? Devin 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.