Katkat

Find Shortest Paths in Road Network

PalantirSoftware Engineer · Onsite

Last updated

This question evaluates understanding of graph data structures and shortest-path concepts, including correct modeling of undirected edges, unweighted versus weighted pathfinding, and algorithmic time and space complexity.

You are reviewing code for a road-network graph.

The domain objects are:

class Location {
 String name;
 Location(String name) { this.name = name; }
}

class Road {
 Location from;
 Location to;
 int distance;
 Road(Location from, Location to, int distance) {
 this.from = from;
 this.to = to;
 this.distance = distance;
 }
}

class RoadConnection {
 Location destination;
 int distance;
 RoadConnection(Location destination, int distance) {
 this.destination = destination;
 this.distance = distance;
 }
}

A Road represents a bidirectional road between two cities. The existing implementation accidentally treats each road as one-way.

Implement or review the graph logic for the following tasks:

  1. Build an adjacency-list representation from a list of Road objects. Make sure roads are handled as bidirectional.
  2. Given two Location objects, return the shortest distance when every road has weight 1. Return -1 if no path exists.
  3. Given two Location objects, return the shortest total distance when road distances can be arbitrary non-negative integers. Return -1 if no path exists.

Discuss the expected time and space complexity for each shortest-path method.