Problem 585709 · hard · Level 05 Advanced Algorithms & Graphs

Which Street in Which Order

graphs · Eulerian path · Hierholzer

Build an Eulerian circuit of an undirected graph and report it as the list of edge indices, in the order the circuit uses them. Return [] when the graph has no Eulerian circuit.

To make the answer unique, follow this exact procedure. Each node keeps its incident edge indices in increasing order. Start at the smallest node that has an edge; push it on a stack. Repeatedly look at the node on top: skip over any of its incident edges that are already used, and if one remains, mark it used and push the node at its other end; otherwise pop the node and write down the edge that brought it there. Reverse the written list at the end.

Write euler_edge_order(n, edges).

Examples

Input:  n = 3, edges = [(1, 2), (2, 0), (0, 1)]
Output: [1, 0, 2]
Explanation: starting at node 0, its smallest incident edge is index 1.

Input:  n = 4, edges = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
Output: []
Explanation: every node has degree 3, so no Eulerian circuit exists.

Constraints

  • 1 <= n <= 10**4, 0 <= len(edges) <= 10**5
  • Self-loops and repeated edges may appear.
  • Keep a cursor per node so each incident list is scanned only once in total; rescanning it each visit is too slow.

Goals

  • Run Hierholzer on an undirected multigraph, where each edge must be retired from both ends
  • Advance a per-node cursor so the whole construction stays linear
  • Return the edges in the order the circuit uses them
Starting Python…