Implement a directed graph with node and edge operations and a lexicographically smallest shortest path
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design and implement a directed graph data structure from scratch. The graph supports adding and removing nodes and edges, checking whether a node or an edge exists, and listing the neighbors of a node.
The graph also supports finding a path between two nodes. The path must be a shortest one (fewest edges). If several shortest paths exist, return the lexicographically smallest one, comparing paths node by node. If no path exists, return an empty list.
All node values are strings. The graph is directed, so an edge from `A` to `B` does not imply an edge from `B` to `A`.
Implement these methods:
- `addNode(node: str)`: add a node to the graph. If the node already exists, do nothing.
- `removeNode(node: str)`: remove a node and every edge that starts or ends at it. If the node does not exist, do nothing.
- `addEdge(src: str, dst: str)`: add a directed edge from `src` to `dst`. Both nodes are added to the graph if they are not already present.
- `removeEdge(src: str, dst: str)`: remove the directed edge from `src` to `dst`. If the edge does not exist, do nothing.
- `hasNode(node: str) -> bool`: return `True` if the node exists in the graph, otherwise `False`.
- `hasEdge(src: str, dst: str) -> bool`: return `True` if a directed edge from `src` to `dst` exists, otherwise `False`.
- `getNeighbors(node: str) -> List[str]`: return a sorted list of all nodes that `node` has a directed edge to. Return an empty list if the node does not exist.
- `findPath(src: str, dst: str) -> List[str]`: use BFS to find and return the lexicographically smallest shortest path from `src` to `dst`. Return an empty list if no path exists or if either node does not exist.
Example 1, a tie between two shortest paths and then a node removal:
```text
g = Graph()
g.addEdge("A", "B")
g.addEdge("A", "C")
g.addEdge("B", "D")
g.addEdge("C", "D")
g.addEdge("D", "E")
g.getNeighbors("A") -> ["B", "C"]
g.findPath("A", "E") -> ["A", "B", "D", "E"]
g.hasEdge("B", "A") -> False
g.removeNode("B")
g.hasNode("B") -> False
g.hasEdge("A", "B") -> False
g.findPath("A", "E") -> ["A", "C", "D", "E"]
g.findPath("E", "A") -> []
```
Both `A, B, D, E` and `A, C, D, E` use three edges, and `B` sorts before `C`, so the first is returned. Removing `B` also removes the edge from `A` to `B`, which leaves only the path through `C`. `E` has no outgoing edges, so nothing is reachable from it.
Example 2, where length decides before lexicographic order:
```text
g = Graph()
g.addEdge("A", "B")
g.addEdge("B", "C")
g.addEdge("C", "Z")
g.addEdge("A", "Y")
g.addEdge("Y", "Z")
g.findPath("A", "Z") -> ["A", "Y", "Z"]
```
`A, B, C, Z` sorts before `A, Y, Z`, but it uses three edges and `A, Y, Z` uses two, so the shorter path is returned.
```hint Which parent to keep
In BFS a node's parent is normally fixed the first time the node is discovered. Work out the order in which neighbors must be expanded so that this first discovery is also the lexicographically smallest way to reach the node.
```
```hint Edges into a removed node
The adjacency map is keyed by the source node, so the edges that point at a node are not stored with that node. Decide how `removeNode` finds them and what that costs.
```
### Constraints & Assumptions
- Node values are strings of length 1 to 20.
- At most 1000 calls are made across all methods.
- No duplicate edge is ever added.
- Removing a node or an edge that does not exist is a no-op and raises no error.
- The graph is directed.
- `findPath(x, x)` for an existing node `x` returns `[x]`.
- Paths are compared element by element using ordinary string comparison, so `["A", "AB"]` sorts before `["A", "B"]`.
### Clarifying Questions to Ask
- Are self-loops, such as an edge from `A` to `A`, allowed?
- Should `getNeighbors` return a fresh list that the caller can change without affecting the graph?
- Does lexicographic order mean plain code-point comparison of the node strings, or a locale-aware order?
- Will more than one thread call the graph at the same time?
### What a Strong Answer Covers
- A representation that keeps nodes with no edges and answers `hasNode`, `hasEdge` and `addEdge` in constant average time.
- A `removeNode` that deletes incoming as well as outgoing edges, with its cost stated and a way to reduce it.
- A BFS that returns a shortest path, plus an argument for why the visiting order makes it the lexicographically smallest among the shortest paths.
- Edge cases: missing nodes, `src` equal to `dst`, self-loops, unreachable targets, and queries that must not create nodes as a side effect.
- The time and space cost of each method, including the cost of sorting neighbors.
### Follow-up Questions
- How would you make `removeNode` run in time proportional to the number of edges touching the node?
- How would `findPath` change if edges had positive weights and the same tie-break applied?
- The graph changes rarely but `findPath` is called many times. What would you precompute or cache?
- What would you change so that several threads can call the class safely?
Overview: Build a directed graph class with string nodes that supports adding and removing nodes and edges, existence checks, sorted neighbor lists and a path query. The path query must return a shortest path and break ties by lexicographic order. It tests adjacency list design, clean removal of incoming edges and reasoning about breadth-first search.