15% off all plans & roadmaps Use code
See plansLeetCode 1129 · Solution & editorial
Consider a directed graph, with nodes labelled 0, 1, ..., n-1. In this graph, each edge is either red or blue, and there could be self-edges or parallel edges.
Shortest Path with Alternating Colors is a Graph Traversal Patterns (DFS & BFS) problem, in the Shortest Path (Bellman-Ford / BFS+K) subpattern. The pattern covers DFS/BFS traversal, topological sort, shortest paths, Union-Find, and MST
Find shortest paths with constraints using Bellman-Ford algorithm and BFS with limited stops.
The reference solution runs in O(n + e) time and O(n + e) space.
Shortest Path with Alternating Colors has been reported in interviews at Amazon.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Shortest Path with Alternating Colors is a Graph Traversal Patterns (DFS & BFS) problem, in the Shortest Path (Bellman-Ford / BFS+K) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.