Leetcode #1129: Shortest Path with Alternating Colors
In this guide, we solve Leetcode #1129 Shortest Path with Alternating Colors in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Breadth-First Search, Graph
Intuition
The data forms a graph, so we should explore nodes and edges systematically.
A traversal ensures we visit each node once while maintaining the needed state.
Approach
Build an adjacency list and traverse with BFS or DFS.
Aggregate results as you visit nodes.
Steps:
- Build the graph.
- Traverse with BFS/DFS.
- Accumulate the required output.
Example
Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []
Output: [0,1,-1]
Python Solution
class Solution:
def shortestAlternatingPaths(
self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]
) -> List[int]:
g = [defaultdict(list), defaultdict(list)]
for i, j in redEdges:
g[0][i].append(j)
for i, j in blueEdges:
g[1][i].append(j)
ans = [-1] * n
vis = set()
q = deque([(0, 0), (0, 1)])
d = 0
while q:
for _ in range(len(q)):
i, c = q.popleft()
if ans[i] == -1:
ans[i] = d
vis.add((i, c))
c ^= 1
for j in g[c][i]:
if (j, c) not in vis:
q.append((j, c))
d += 1
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.