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?- A. PQT PQT
- B. PRSPQT PQT
- C. PRSPQT PRSPQT
- 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
- Problem: Assign interns to projects; intern u may take only projects in adj[u], each project at most one intern. Maximum bipartite…
- Problem: For every warehouse in a tree network, compute the sum of distances to all other warehouses with two passes (rerooting)…
- Problem: Count integers in [1, N] divisible by at least one of the given numbers using inclusion–exclusion with LCMs (N up to 10⁹, so no…
- Problem: Compute C(n, r) mod a SMALL prime p = 7 when n ≥ p: Lucas' theorem versus factorials with Fermat inverses. python p = 7 fact =…
- Problem: Count ways to climb n stairs with steps of 1 or 3, modulo 10⁹ + 7, using a 3 × 3 matrix power so that n up to 10¹⁸ is fine…
- Problem: Peak number of simultaneous bookings with a sweep line. In the first call intervals are CLOSED [s, e] (a booking ending at 3 and…