Euler Path and Circuit - Problem

An Euler path is a path in a graph that visits every edge exactly once. An Euler circuit is an Euler path that starts and ends at the same vertex.

Given a graph represented as an adjacency list, determine if the graph has an Euler path or circuit, and if so, return the path. Use Hierholzer's algorithm to find the path efficiently.

The graph can be either directed or undirected. For undirected graphs, an Euler path exists if and only if the graph is connected and has exactly 0 or 2 vertices with odd degree. For directed graphs, an Euler path exists if the graph is weakly connected and has at most one vertex with out-degree - in-degree = 1, at most one vertex with in-degree - out-degree = 1, and all other vertices have equal in-degree and out-degree.

Return the Euler path/circuit as an array of vertices, or an empty array if no such path exists.

Input & Output

Example 1 — Simple Triangle Circuit
$ Input: graph = [[1], [2], [0]], isDirected = false
Output: [0, 1, 2, 0]
💡 Note: Undirected triangle: 0→1→2→0. All vertices have degree 2 (even), so Euler circuit exists starting from any vertex.
Example 2 — Directed Path
$ Input: graph = [[1], [2], []], isDirected = true
Output: [0, 1, 2]
💡 Note: Directed path: 0→1→2. Vertex 0 has out-degree 1, in-degree 0. Vertex 2 has out-degree 0, in-degree 1. Valid Euler path.
Example 3 — No Euler Path
$ Input: graph = [[1, 2], [0], [0]], isDirected = false
Output: []
💡 Note: Vertex 0 has degree 3, vertices 1 and 2 have degree 1. Three vertices with odd degree - no Euler path possible.

Constraints

  • 1 ≤ graph.length ≤ 1000
  • 0 ≤ graph[i].length ≤ 1000
  • 0 ≤ graph[i][j] < graph.length
  • isDirected is either true or false

Visualization

Tap to expand
INPUT GRAPHALGORITHM STEPSEULER PATH012graph = [[1,2],[2],[1]]isDirected = false1Check degrees: all even2Start from vertex 03Build circuit: 0→1→24Continue: 2→0 (stuck)5Complete path found!012Path: [0, 1, 2, 0]All edges visited onceKey Insight:Hierholzer's algorithm builds Euler paths by creating circuits and merging them,rather than trying to plan the entire route upfront. Check degree conditions first!TutorialsPoint - Euler Path and Circuit | Hierholzer's Algorithm
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
12.4K Views
Medium Frequency
~35 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen