Find Shortest Paths in Road Network
PalantirSoftware Engineer · OnsiteLast 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:
- Build an adjacency-list representation from a list of
Roadobjects. Make sure roads are handled as bidirectional. - Given two
Locationobjects, return the shortest distance when every road has weight1. Return-1if no path exists. - Given two
Locationobjects, return the shortest total distance when road distances can be arbitrary non-negative integers. Return-1if no path exists.
Discuss the expected time and space complexity for each shortest-path method.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.