If , vertex has no outgoing edge. Therefore, if a Hamiltonian path exists, vertex must be the last vertex of the path.
Similarly, if , vertex has no outgoing edge. Hence vertex must also be the last vertex of any Hamiltonian path.
Therefore, when and , two distinct vertices would both have to be the last vertex, so no Hamiltonian path exists.
In every other case, we can construct a Hamiltonian path directly.
Suppose . First output all vertices with in increasing order, then output all vertices with in decreasing order. Inside the first part, the current vertex has value and the next vertex has a larger number, so the required edge always exists. Inside the second part, the current vertex has value and the next vertex has a smaller number, so the required edge always exists. If both parts are nonempty, the last vertex of the first part is smaller than , while the first vertex of the second part is . Thus the edge between the two parts also exists.
If , then because we are not in the impossible case, . Output all vertices with in decreasing order, then all vertices with in increasing order. Edges inside each part exist for the same reason as above. If both parts are nonempty, the last vertex of the first part is greater than , while the first vertex of the second part is , so the edge between the two parts also exists.
Each vertex is processed only a constant number of times. Thus the time complexity is per test case and overall. The extra space complexity is .
Solution written by GPT5.6