Find the Second-Fastest Backup Route Between Two Hubs

Last updated: November 29, 2026

Quick Overview

For resilience planning, find the travel time of the strictly second shortest route from hub 0 to hub n - 1 in a weighted undirected graph. Routes may revisit nodes; return -1 if no such route exists.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


For resilience planning, find the travel time of the strictly second shortest route from hub 0 to hub n - 1 in a weighted undirected graph. Routes may revisit nodes; return -1 if no such route exists.

Amazon middle-mile planners keep a backup lane in case the primary is disrupted. Interviewers use this to see whether you can generalize Dijkstra to keep the top two distinct distances per node and reason about why revisits are allowed.

What the Interviewer Expects
  • Keep two distances per node: best and strictly second best
  • Push a state whenever it improves either slot
  • Handle the swap when a new best displaces the old best
  • Ensure the second is strictly greater than the first
  • Explain the complexity: each node is settled at most twice
Key Topics to Cover
Dijkstra
k shortest paths
weighted graphs
state duplication
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you generalize to the k-th shortest route (Yen or Eppstein)?
  • What if the backup route must not share any road with the fastest one?
  • How would the answer change if routes had to be simple paths?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: n hubs and undirected roads (u, v, w) with positive weights. Output: the smallest route time strictly greater than the shortest time from 0 to n - 1. A route can repeat roads (for example g...

High-Level Design

Maintain d1[v] and d2[v]. Pop (d, u) from a heap; skip it if d > d2[u]. For each edge, nd = d + w. If nd < d1[v], move d1 into d2, set d1 = nd and push both. Else if d1[v] < nd < d2[v], ...


Submit Your Answer
Markdown supported