The Shortest Path with Alternating Colors interview question gives you a directed graph with edges colored either red or blue. Find the shortest path from node 0 to every other node using paths where edge colors strictly alternate (red-blue-red-blue... or blue-red-blue-red...). If a node is unreachable via any alternating-color path, return -1 for that node.
Sprinklr, Microsoft, and Amazon ask this problem because it tests BFS with edge-color state augmentation — a clean extension of standard BFS where the state includes both the current node AND the last edge color used. This models real-world alternating-constraint routing: time-division multiplexed networks, alternating protocol communication, and multi-layer network path validation.
The pattern is BFS with state (node, last_color). Initialize the queue with (0, RED) and (0, BLUE) at distance 0 (node 0 is reachable from itself with either color as the next edge). For each state, traverse only edges of the OPPOSITE color. Mark visited states as (node, color) — not just (node) — since a node may be reachable with different remaining-color constraints. Track minimum distance for each node across both color entry states.
Graph: red edges 0→1, 1→2. Blue edges 0→2, 2→1.
BFS:
Result: node 0=0, node 1=1, node 2=1.
(node) only — without color state, nodes reachable only via a specific alternating sequence are missed.For the Shortest Path with Alternating Colors coding problem, the BFS graph interview pattern with state augmentation is the approach. The state (node, last_color) is the critical extension — it allows BFS to correctly track which edges can be traversed next. Microsoft and Amazon interviewers test whether candidates immediately identify the need for color in the state. Practice augmented-state BFS — it generalizes to any graph traversal where transitions depend on historical context (last move, remaining resources, etc.).
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Shortest Cycle in a Graph | Hard | Solve | |
| Reorder Routes to Make All Paths Lead to the City Zero | Medium | Solve | |
| Shortest Distance After Road Addition Queries I | Medium | Solve | |
| Keys and Rooms | Medium | Solve | |
| Count the Number of Houses at a Certain Distance I | Medium | Solve |