function teleportersPath(n, edges):
inDeg = array of 0s
outDeg = array of 0s
adj = adjacency list
for each edge (u, v):
outDeg[u] = outDeg[u] + 1
inDeg[v] = inDeg[v] + 1
adj[u].append(v)
// Check conditions
if outDeg[1] != inDeg[1] + 1:
return "IMPOSSIBLE"
if inDeg[n] != outDeg[n] + 1:
return "IMPOSSIBLE"
for v from 2 to n-1:
if inDeg[v] != outDeg[v]:
return "IMPOSSIBLE"
// Run Hierholzer from vertex 1
return hierholzer(adj, 1)
This runs in time and uses space.