Existence
A vertex of degree forces an immediate traversal back along the same edge, so no solution exists. Conversely, minimum degree at least is sufficient. Bridges do not prevent a solution.
Construction
Duplicate every edge and find an Euler circuit with Hierholzer's algorithm. Each original edge is now traversed twice. Call two consecutive uses of the same original edge a U-turn, including the junction between the last and first edges.
Choose a U-turn . Since has degree at least , the circuit has another visit . Both uses of edge are already in the chosen U-turn, so and . It is possible that .
Reverse the segment between the two visits. The two junctions become and , neither of which is a U-turn. Inside the reversed segment, only the direction changes, so U-turn status is unchanged. The walk remains closed and every edge keeps its traversal count. Thus at least one U-turn disappears and none is created.
Initially there are at most U-turns, since each one uses both copies of a different original edge. Finding a U-turn, finding another visit, and reversing the segment each take time. Total time is and space is . Across test cases, time is at most . Connectivity gives .
Subtasks
For subtask 1, use a ternary mask to store each edge's usage count in . Fix the first input edge as the first traversal in one direction. Any valid circuit can be rotated and, if needed, reversed to satisfy this choice. Memoize failed states consisting of the current vertex, previous edge, and ternary mask. Time is and space is . The bounds and make this feasible.
For subtask 2, a connected graph of maximum degree at most is a path or a cycle. A path is impossible; traverse a cycle twice in the same direction. Time and space are .
Subtask 3 uses the U-turn removal algorithm above.
Solution written by GPT