Find shortest path with blocked nodes
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in graph traversal and shortest-path computation, including handling nodes that are blocked or that incur additional costs. It is commonly asked in the coding and algorithms domain (graph algorithms) to assess both practical implementation skills and conceptual understanding of complexity, edge cases, and trade-offs between unweighted and weighted path models.
Constraints
- 1 <= n <= 200000
- 0 <= len(edges) <= 200000
- 0 <= start, end < n
- Node labels are integers in [0, n-1]
- Graph is undirected and unweighted
- Nodes in blocked cannot be stepped on; if start or end is blocked, return -1
- Return -1 if no path exists
- Edges may contain duplicates or self-loops; ignore duplicates naturally
Solution
from collections import deque
from typing import List
def shortest_blocked_path(n: int, edges: List[List[int]], start: int, end: int, blocked: List[int]) -> int:
blocked_set = set(blocked)
if start in blocked_set or end in blocked_set:
return -1
if start == end:
return 0
adj = [[] for _ in range(n)]
for e in edges:
if len(e) != 2:
continue
u, v = e
if 0 <= u < n and 0 <= v < n:
adj[u].append(v)
adj[v].append(u)
visited = [False] * n
q = deque([start])
visited[start] = True
dist = 0
while q:
size = len(q)
for _ in range(size):
u = q.popleft()
if u == end:
return dist
for w in adj[u]:
if not visited[w] and w not in blocked_set:
visited[w] = True
q.append(w)
dist += 1
return -1
Explanation
Time complexity: O(n + m), where m = len(edges). Space complexity: O(n + m).
Hints
- Use BFS from start while skipping any neighbor that is blocked or already visited.
- Return the level at which you first dequeue end; if start == end and not blocked, the answer is 0.
- For space optimization, consider bidirectional BFS from start and end on the unblocked subgraph.
- If blocked nodes are traversable with extra cost, model entering a blocked node as higher edge weight and use Dijkstra's algorithm.