Shortest Path with Alternating Colors - Solution & Explanation
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.
You are given two arrays redEdges and blueEdges where:
redEdges[i] = [ai, bi]indicates that there is a directed red edge from nodeaito nodebiin the graph, andblueEdges[j] = [uj, vj]indicates that there is a directed blue edge from nodeujto nodevjin the graph.
Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist.
Example 1:
Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = [] Output: [0,1,-1]
Example 2:
Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]] Output: [0,1,-1]
Constraints:
1 <= n <= 1000 <= redEdges.length, blueEdges.length <= 400redEdges[i].length == blueEdges[j].length == 20 <= ai, bi, uj, vj < n
Approach Overview
Problem Overview: Given a directed graph with red and blue edges, compute the shortest distance from node 0 to every other node such that the path alternates colors at each step. If no alternating path exists, return -1 for that node.
Approach 1: BFS with State Tracking (O(n + r + b) time, O(n) space)
This problem behaves like a shortest path search on a graph where the state includes both the node and the color of the edge used to reach it. Use Breadth-First Search starting from node 0. Instead of marking only nodes as visited, track (node, lastColor) to enforce alternation. Build two adjacency lists for red and blue edges, push both starting states into the queue, and expand only edges of the opposite color. BFS guarantees the first time you reach a node with a valid color sequence is the shortest alternating distance. This approach is simple and works efficiently because each state is processed at most once.
Approach 2: Layered BFS with Two Queues (O(n + r + b) time, O(n) space)
Another way to enforce color alternation is to maintain two queues: one for paths that ended with a red edge and one for paths that ended with a blue edge. During each BFS layer, process nodes from one queue and expand only edges of the opposite color into the other queue. Distances are updated level by level, similar to standard BFS on an unweighted graph. This structure separates transitions clearly and avoids repeatedly checking edge colors inside the same queue. The algorithm still processes each edge at most once per color state, keeping the complexity linear.
Recommended for interviews: BFS with state tracking is the most common interview solution. It directly models the constraint by extending the BFS state to include the previous edge color. Explaining this transition clearly shows you understand how to adapt BFS for constrained shortest-path problems.
Approach 1: BFS with State Tracking
Use a Breadth-First Search (BFS) to traverse the graph, keeping track of the last edge color used (red or blue). This can be done using a queue where each element is a tuple containing the current node, distance traveled, and the color of the edge used to arrive at this node. We need two visited arrays to track if a node has been visited with a red edge or a blue edge to avoid re-processing.
The solution first constructs adjacency lists for red and blue edges. A deque is used for BFS which starts from node 0 with a distance of 0. For each node, it checks the next possible nodes via red or blue edges, ensuring no repeated visits are made using the same edge color. It updates the shortest distance for each node when it is first reached, ensuring paths alternate between red and blue.
Code
Python
JavaScript
Complexity
Time Complexity: O(n + redEdges.length + blueEdges.length) - This accounts for the BFS traversal and the construction of adjacency lists.
Space Complexity: O(n) - This is the space required for visited sets and the BFS queue.
Approach 2: Layered BFS with Two Queues
This approach involves using two separate BFS queues to handle paths starting with red and blue edges. By maintaining distinct queues for red and blue path exploration, the solution ensures color alternation by construction, processing nodes layer by layer from each starting color queue separately.
This Java implementation operates with two BFS queues dedicated for red and blue starting paths. The strategy processes node connections based on the opposite color adjacency list, alternatively updating shortest paths. Each queue contributes towards a layer of nodes processed, ensuring paths alternate colors efficiently with minimized total distances computed.
Complexity
Time Complexity: O(n + redEdges.length + blueEdges.length) - The layer processing replicates BFS traversal cost.
Space Complexity: O(n) - Needed for separate visitation states and queue management.
Approach 3: BFS
The problem is essentially a shortest path problem, which we can consider solving using BFS.
First, we preprocess all the edges, categorizing all the edges by color and storing them in a multi-dimensional array g. Where g[0] stores all red edges, and g[1] stores all blue edges.
Next, we define the following data structures or variables:
- Queue
q: used to store the currently searched node and the color of the current edge; - Set
vis: used to store the nodes that have been searched and the color of the current edge; - Variable
d: used to represent the current search level, i.e., the distance from the currently searched node to the starting point; - Array
ans: used to store the shortest distance from each node to the starting point. Initially, we initialize all elements in theansarray to-1, indicating that the distance from all nodes to the starting point is unknown.
We first enqueue the starting point 0 and the color of the starting edge 0 or 1, indicating that we start from the starting point and the current edge is red or blue.
Next, we start the BFS search. Each time we take out a node (i, c) from the queue, if the answer of the current node has not been updated, then we update the answer of the current node to the current level d, i.e., ans[i] = d. Then, we flip the color of the current edge c, i.e., if the current edge is red, we change it to blue, and vice versa. We take out all edges corresponding to the color, if the other end node j of the edge has not been searched, then we enqueue it.
After the search is over, return the answer array.
The time complexity is O(n + m), and the space complexity is O(n + m). Here, n and m are the number of nodes and edges, respectively.
Code
Python
Java
C++
Go
TypeScript
Complexity Comparison
| Approach | Complexity |
|---|---|
| BFS with State Tracking | Time Complexity: O(n + redEdges.length + blueEdges.length) - This accounts for the BFS traversal and the construction of adjacency lists. |
| Layered BFS with Two Queues | Time Complexity: O(n + redEdges.length + blueEdges.length) - The layer processing replicates BFS traversal cost. |
| BFS | — |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| BFS with State Tracking | O(n + r + b) | O(n) | General solution for alternating edge constraints; clean and commonly expected in interviews |
| Layered BFS with Two Queues | O(n + r + b) | O(n) | Useful when separating states by edge color improves clarity or simplifies implementation |
Video Solution
Shortest Path with Alternating Colors - Leetcode 1129 - Python • NeetCodeIO • 19,055 views views
Watch 9 more video solutions →Frequently Asked Questions
Is Shortest Path with Alternating Colors easy or hard?
Shortest Path with Alternating Colors Python/Java solution
How to solve Shortest Path with Alternating Colors in O(n)?
What is the best approach for Shortest Path with Alternating Colors?
Is Shortest Path with Alternating Colors asked at Google/Amazon/Meta?
What data structure is used in Shortest Path with Alternating Colors?
What is the time complexity of Shortest Path with Alternating Colors?
Ready to solve this problem?
Practice Shortest Path with Alternating Colors with our built-in code editor and test cases.
Practice on FleetCode