← Whiteboard questions

Reconstruct Itinerary

Find the alphabetically first route that uses every one-way tunnel once

DSA, Hard, Advanced Graphs

Which structure or algorithm, and what does it cost.

A courier starts at the stop "HUB". Each pair [from, to] in tunnels is a one-way tunnel. The courier must drive through every tunnel exactly once. Return the stops in the order visited, starting with "HUB". A route that uses every tunnel always exists. If several routes work, return the one that comes first alphabetically when you compare stop by stop. Two tunnels may join the same stops, and a tunnel may lead back to its own stop.

Examples

Input tunnels = [["HUB","MIX"],["MIX","BAY"],["BAY","HUB"],["HUB","ARC"]]
Output ["HUB","MIX","BAY","HUB","ARC"]
Why ARC is the smallest stop after HUB, but it is a dead end, so it must come last.
Input tunnels = [["HUB","ELM"],["ELM","HUB"],["HUB","DOT"],["DOT","HUB"],["HUB","ELM"]]
Output ["HUB","DOT","HUB","ELM","HUB","ELM"]
Why DOT is smaller than ELM, and the two tunnels from HUB to ELM are each used once.
Input tunnels = [["HUB","HUB"],["HUB","HUB"]]
Output ["HUB","HUB","HUB"]
Why both tunnels lead back to HUB, so the route stays at HUB.

Constraints

Your answer must contain

Target Aim for O(r log r) time and O(r) memory, where r is the number of tunnels.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Draw stops as dots and tunnels as arrows. You need a walk that uses every arrow once. What goes wrong if you always take the smallest next stop?

Hint 2 the approach

Plan for dead ends before you commit to a tunnel. A stop with no way out can only be the end of what is left of the route.

Hint 3 the key step

Keep a stack of the walk. When the top stop has no tunnel left, pop it into the answer. When the stack is empty, reverse the answer.

Walkthrough

Full walkthrough brute force to best

Brute force

Try every order of the tunnels. Keep the orders that start at HUB and chain from stop to stop, then pick the alphabetically first. With r tunnels there are r! orders, so this only works for a handful of tunnels.

Best method

Sort the tunnels so each stop lists its next stops from largest to smallest. Popping from the end of a list then gives the smallest. Keep a stack that starts with HUB. While the top stop has an unused tunnel, take its smallest one and push the next stop. When the top stop has none left, pop it and add it to the answer. A stop is popped only after every tunnel leaving it is used, so a dead end is popped first and lands last in the route. Reverse the answer at the end. Each stop tries its smallest unused tunnel first, and a stop moves later in the route only when it is a dead end. So each place in the route gets the smallest stop that still lets the route finish. This method is called Hierholzer's algorithm. It finds a walk that uses every edge of a graph exactly once.

Hand trace

Example 1: HUB lists [ARC, MIX] with ARC first, MIX lists [BAY], BAY lists [HUB]. The stack starts as [HUB]. Take ARC: the stack is [HUB, ARC]. ARC has no tunnel left, so pop it: the answer is [ARC]. Back at HUB, take MIX, then BAY, then HUB: the stack is [HUB, MIX, BAY, HUB]. This HUB has no tunnel left, so pop HUB, BAY, MIX and HUB in turn: the answer is [ARC, HUB, BAY, MIX, HUB]. Reversed, the route is HUB, MIX, BAY, HUB, ARC.

Code

def find_route(tunnels):
    out = {}
    for a, b in sorted(tunnels, reverse=True):      # largest first, so pop() gives the smallest
        out.setdefault(a, []).append(b)
    stack, route = ["HUB"], []
    while stack:
        if out.get(stack[-1]):
            stack.append(out[stack[-1]].pop())      # take the smallest unused tunnel
        else:
            route.append(stack.pop())               # stuck: this stop goes last among the rest
    return route[::-1]

Time and memory

O(r log r) time, from the sort. Each tunnel is then used once. O(r) memory for the lists, the stack and the answer, where r is the number of tunnels.

Common mistakes

  • Taking the smallest stop with no way back. The walk can enter a dead end and leave tunnels unused, as ARC does in example 1.
  • Adding a stop to the answer when you first reach it. Add it only when it is popped with no tunnel left, then reverse the answer.
  • Keeping the tunnels in a set. Two tunnels can join the same stops, so keep a list and use each copy once.
  • Taking the smallest stop with pop(0) on a sorted list. That shifts the whole list each time. Sort in reverse and pop from the end, or keep an index.

Related problems

More Advanced Graphs problems
Reconstruct Itinerary: walkthrough and Python solution