Skip to lesson

Euler paths and circuits

An Eulerian path visits every edge in a graph exactly once and can be found in linear O(V + E) time.

Euler paths versus Hamiltonian paths

Leonhard Euler founded graph theory in 1736 solving the Seven Bridges of Königsberg puzzle. An Eulerian path traverses every edge in the graph exactly once. An Eulerian circuit is an Eulerian path that starts and ends at the exact same vertex.

Example 1 · Degree Parity Check for Eulerian Path Existence

EulerDegreeCheckDemo.javaJava
public class EulerDegreeCheckDemo {    public static String checkEuler(int n, int[][] edges) {        int[] degree = new int[n];        for (int[] e : edges) {            degree[e[0]]++;            degree[e[1]]++;        }
        int oddCount = 0;        for (int d : degree) {            if (d % 2 != 0) oddCount++;        }
        if (oddCount == 0) return "Euler Circuit";        if (oddCount == 2) return "Euler Path";        return "None";    }
    public static void main(String[] args) {        // Triangle: degrees all 2        int[][] e1 = {{0, 1}, {1, 2}, {2, 0}};        // Line of 3 nodes: degrees 1, 2, 1        int[][] e2 = {{0, 1}, {1, 2}};        // Star graph: degrees 3, 1, 1, 1        int[][] e3 = {{0, 1}, {0, 2}, {0, 3}};
        System.out.println("Triangle: " + checkEuler(3, e1));        System.out.println("Line: " + checkEuler(3, e2));        System.out.println("Star: " + checkEuler(4, e3));    }}
Output
Triangle: Euler Circuit
Line: Euler Path
Star: None

What this code does

  • Counts degrees of all vertices across the undirected edge list.
  • Reports Euler Circuit when all degrees are even, and Euler Path when exactly two are odd.
  • Returns None when four vertices have odd degree in the star graph.

In contrast, a Hamiltonian path visits every vertex in the graph exactly once. Finding a Hamiltonian path is NP-complete, requiring exponential search in the worst case. Finding an Eulerian path, however, runs in pure linear O(V + E) time. Euler proved that edge traversability depends entirely on vertex degree parity. In an undirected graph, an Euler circuit exists if all vertex degrees are even. An Euler path exists if exactly two vertices have odd degree. Those two odd-degree vertices must serve as the start and end of the path. All intermediate vertices must have even degree to enter and exit equally.

Predict the output

Predict the odd-degree count

Read the code and pick what it prints.

What does this program print?

public class Main {
public static void main(String[] args) {
int[][] edges = {{0, 1}, {1, 2}, {2, 0}, {2, 3}};
int[] degree = new int[4];
for (int[] e : edges) {
degree[e[0]]++;
degree[e[1]]++;
}
int odd = 0;
for (int d : degree) if (d % 2 == 1) odd++;
System.out.println("Odd-degree vertices: " + odd);
}
}

Hierholzer algorithm: post-order edge traversal

A greedy DFS that arbitrarily chooses edges can enter a dead end prematurely. If it stops before visiting all edges, detached sub-cycles are left behind abandoned. Hierholzer's algorithm solves this by traversing edges and building the path in post-order.

Example 2 · Eulerian Path on an Undirected Graph

UndirectedEulerPathDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.LinkedList;import java.util.List;
public class UndirectedEulerPathDemo {    public static List<Integer> getEulerPath(int n, int[][] edges) {        int[][] adj = new int[n][n];        int[] degree = new int[n];        for (int[] e : edges) {            adj[e[0]][e[1]]++;            adj[e[1]][e[0]]++;            degree[e[0]]++;            degree[e[1]]++;        }
        int start = 0;        for (int i = 0; i < n; i++) {            if (degree[i] % 2 != 0) {                start = i;                break;            }        }
        LinkedList<Integer> path = new LinkedList<>();        dfs(start, n, adj, path);        return path;    }
    private static void dfs(int u, int n, int[][] adj, LinkedList<Integer> path) {        for (int v = 0; v < n; v++) {            while (adj[u][v] > 0) {                adj[u][v]--;                adj[v][u]--;                dfs(v, n, adj, path);            }        }        path.addFirst(u);    }
    public static void main(String[] args) {        int n = 4;        // Path starting at 0: 0-1, 1-2, 2-3, 3-1        int[][] edges = {{0, 1}, {1, 2}, {2, 3}, {3, 1}};        List<Integer> path = getEulerPath(n, edges);        System.out.println("Euler path: " + path);    }}
Output
Euler path: [0, 1, 2, 3, 1]

What this code does

  • Selects starting vertex having an odd degree (vertex 0 has degree 1).
  • Removes undirected edges dynamically during recursion to prevent reuse.
  • Reconstructs the full 4-edge Eulerian sequence [0, 1, 2, 3, 1].

The algorithm follows unused edges from the current vertex until reaching a dead end. When a vertex has no remaining outgoing edges, push it onto an itinerary stack. It then backtracks to earlier vertices that still have unexplored outgoing edges. Traversing those remaining sub-cycles splices them seamlessly into the main tour. Reversing the post-order itinerary list at the end yields the complete Eulerian sequence. Hierholzer's algorithm processes each edge exactly once, achieving linear O(V + E) runtime. This guarantees visiting every edge without getting stranded.

Reconstructing flight itineraries and De Bruijn sequences

A classic interview problem models airline tickets as directed edges between airport vertices. Given tickets, reconstruct the itinerary starting from "JFK" in lexicographical order. Priority queues for each airport's outgoing flights ensure alphabetical selection. Hierholzer's post-order DFS guarantees all flights are used without stranding.

Example 3 · Hierholzer Algorithm for Flight Itinerary Reconstruction

ReconstructItineraryDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.PriorityQueue;
public class ReconstructItineraryDemo {    public static List<String> findItinerary(List<List<String>> tickets) {        Map<String, PriorityQueue<String>> adj = new HashMap<>();        for (List<String> t : tickets) {            adj.computeIfAbsent(t.get(0), k -> new PriorityQueue<>()).offer(t.get(1));        }
        LinkedList<String> itinerary = new LinkedList<>();        dfs("JFK", adj, itinerary);        return itinerary;    }
    private static void dfs(String airport, Map<String, PriorityQueue<String>> adj, LinkedList<String> itinerary) {        PriorityQueue<String> dests = adj.get(airport);        while (dests != null && !dests.isEmpty()) {            dfs(dests.poll(), adj, itinerary);        }        itinerary.addFirst(airport); // Post-order prepend    }
    public static void main(String[] args) {        List<List<String>> tickets = new ArrayList<>();        tickets.add(List.of("MUC", "LHR"));        tickets.add(List.of("JFK", "MUC"));        tickets.add(List.of("SFO", "SJC"));        tickets.add(List.of("LHR", "SFO"));
        List<String> path = findItinerary(tickets);        System.out.println("Itinerary: " + path);    }}
Output
Itinerary: [JFK, MUC, LHR, SFO, SJC]

What this code does

  • Organises destinations in min-heaps to prioritise alphabetically smaller airports.
  • Executes Hierholzer's post-order traversal and prepends exhausted nodes to the itinerary.
  • Outputs the complete reconstructed flight route [JFK, MUC, LHR, SFO, SJC].

Bioinformatics uses Eulerian paths to reconstruct DNA strands from overlapping genetic sequences. Short DNA fragments called k-mers form edges in a De Bruijn graph. An Eulerian path through the De Bruijn graph reconstructs the complete original chromosome. Robotics and street sweeping routing also rely on Eulerian circuits for minimal travel.

Next step

Check your understanding

10 quick questions