Back to the 2024 paper

Module 3: Graph and Tree Algorithms

20247m

Design a system that finds the shortest paths between various locations in a city. The locations and roads are represented using a graph. What algorithm would you use if:
(i) All roads have equal length
(ii) Roads have varying lengths, but no negative lengths
(iii) Some roads have negative lengths
Justify your choices with suitable algorithms and reasoning.

Worked SolutionAI Assisted

Shortest-Path System Design — Choice by Edge Weight

City = graph vertices = locations, edges = roads, weight = length/time.

(i) All roads equal length (unweighted)

Algorithm: Breadth-First Search (BFS)

  • Reason: BFS explores in increasing distance (number of edges) layers → first time target dequeued, its distance is minimum edges. O(V+E)O(V+E) with adjacency list, no need for priority queue.
  • Alternative: Dijkstra with uniform weight 1 reduces to BFS (overhead wasteful).
  • Use queue: dist[s]=0, push neighbors.

(ii) Varying lengths, no negative weights (positive weighted)

Algorithm: Dijkstra's Algorithm (with binary heap O((V+E)log⁡V)O((V+E)\log V), Fibonacci O(E+Vlog⁡V)O(E+V\log V))

  • Reason: Greedy choice of smallest tentative distance; proof relies on non-negative weights (once vertex extracted, distance final). Handles varying positive weights optimal.
  • Steps: dist[s]=0, priority queue keyed by dist; repeatedly extract min uu, relax edges u→vu→v: if dist[u]+w(u,v)<dist[v]dist[u]+w(u,v)<dist[v] update.
  • Why not Bellman-Ford? Correct but O(VE)O(VE) slower, unnecessary without negatives.
  • Why not BFS? BFS assumes uniform weight → would give wrong result.

(iii) Some roads have negative lengths (negative weights, but no negative cycles reachable)

Algorithm: Bellman-Ford Algorithm (O(VE)O(VE)) — or SPFA / Johnson's if many sources.

  • Reason: Dijkstra fails with negative edges (greedy finality broken; example s→as→a weight5, s→bs→b weight6, b→ab→a weight -4 → shortest to aa is via bb (2) not direct 5, Dijkstra would finalize aa too early).
  • Bellman-Ford relaxes all edges V−1V-1 times, then one more pass detects negative cycles.
  • If negative cycle exists, shortest path undefined (−∞-\infty); Bellman-Ford reports it.
  • If graph large and only few negatives, could use Johnson's (O(VElog⁡V)O(VE\log V)) reweighting.

Summary Table

Case Weights Algorithm Time Handles negatives?
(i) uniform BFS O(V+E)O(V+E) No need
(ii) ≥0≥0 varying Dijkstra (heap) O(Elog⁡V)O(E\log V) No
(iii) arbitrary (no neg cycle) Bellman-Ford O(VE)O(VE) Yes + detects cycle

Justification: Choose simplest correct algorithm for constraint; progressing BFS → Dijkstra → Bellman-Ford as generality increases, trading speed for correctness.

Similar questions

Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.