Lexicographically smallest Eulerian circuit

Write codeHard40 min

Your task

Given a directed multigraph on n nodes (0..n-1) with a list of directed edges, reconstruct the lexicographically smallest Eulerian circuit: a closed walk starting and ending at the same node that uses every edge exactly once. Return it as the list of visited nodes (length = number_of_edges + 1). If no Eulerian circuit exists (degree imbalance or the edges are not all connected into one circuit), return an empty list. Start the circuit from the smallest-numbered node that has an outgoing edge. Constraints: 1 <= n <= 1000; edges may include self-loops and parallel edges.

Examples

lex_eulerian_circuit(n: int, edges: list[list[int]]) -> list[int]
Example 1
Inputlex_eulerian_circuit(3, [[0, 1], [1, 2], [2, 0]])
Output[0, 1, 2, 0]