Data Structures & AlgorithmsVery hardProduct company OA

Problem: A drone must fly every route leg exactly once starting at P, choosing the alphabetically smallest destination whenever possible. Hierholzer's algorithm versus 'always fly to the smallest unused destination'.

Problem: A drone must fly every route leg exactly once starting at P, choosing the alphabetically smallest destination whenever possible. Hierholzer's algorithm versus 'always fly to the smallest unused destination'.
from collections import defaultdict
def route(legs, start):
    g = defaultdict(list)
    for a, b in sorted(legs, reverse=True): g[a].append(b)
    st, out = [start], []
    while st:
        while g[st[-1]]: st.append(g[st[-1]].pop())
        out.append(st.pop())
    return "".join(out[::-1])
def greedy(legs, start):
    g = defaultdict(list)
    for a, b in sorted(legs): g[a].append(b)
    cur, out = start, [start]
    while g[cur]:
        cur = g[cur].pop(0); out.append(cur)
    return "".join(out)
legs = [("P", "Q"), ("P", "R"), ("R", "S"), ("S", "P"), ("Q", "T")]
print(route(legs, "P"), greedy(legs, "P"))
What is printed?
  1. A. PQT PQT
  2. B. PRSPQT PQT
  3. C. PRSPQT PRSPQT
  4. D. PQTPRS PQT

Correct answer: B. PRSPQT PQT

Greedy takes P → Q → T and is stuck with P → R → S → P unused. Hierholzer pushes vertices on a stack, follows unused edges until stuck, and emits vertices only when they have no edges left; reversing the emission order splices the detour P → R → S → P into the walk before the dead end: PRSPQT. With legs sorted and popped from the end, it still prefers the smallest destination whenever that does not strand edges. O(E log E).

More Coding Interview Problems questions

Exams that ask this topic