Actually, you have very nearly proved it yourself. The missing part of your proof is to show that if the DAG has a Hamiltonian path, then the topological sorting algorithm must find it, because there is no other way to put the nodes in a topological-sorted order:
Suppose there is a Hamiltonian path. Let u
and v
be any two nodes, and suppose without loss of generality that u
occurs before v
in the Hamiltonian path. Then there is a path from u
to v
formed from the nodes in the Hamiltonian path between u
and v
, so u
must occur before v
in any topological-sorted order.
It follows that all pairs of nodes in a topological-sorted order have the same relative ordering as they have in the Hamiltonian path. Therefore, if the nodes are topologically sorted then they are in the same order as the Hamiltonian path.
Therefore, if there is a Hamiltonian path, running any topological sorting algorithm will find it. The inverse is rather trivial; if there is no Hamiltonian path then of course topological sorting won't find one.
Regarding space complexity, this will be the same as the space complexity of your topological sorting algorithm, because the second stage where you check if the result is a Hamiltonian path takes O(1) extra space. The space complexity of standard topological sorting algorithms is O(n) where n is the number of vertices.