Problem overview
The method shortestAlternatingPaths receives n, the number of nodes in a directed graph labeled 0 to n - 1, and two lists of directed edges: redEdges and blueEdges. The graph may contain self-edges and parallel edges. It returns an array answer of length n, where answer[x] is the length of the shortest path from node 0 to node x in which the edge colors alternate (red, blue, red, ... or blue, red, blue, ...), or -1 if no such path exists.
In the first example, n = 3, with red edges 0 → 1 and 1 → 2 and no blue edges. Node 1 is one red edge away. Node 2 would need a second red edge in a row, which breaks the alternation, so it gets -1: the answer is [0, 1, -1]. In the second example the path 0 --red--> 1 --blue--> 2 alternates, giving [0, 1, 2].
Approach: BFS where a state is a node plus the last color
With every edge counting as one step, breadth-first search (BFS) finds shortest paths. The twist is the colour rule. Whether an edge may be used next depends on the colour of the edge just used, so reaching node v is not one situation but two: arriving by a red edge, which allows only blue edges next, or arriving by a blue edge, which allows only red edges next. The same node can be useful in both situations, and the two continue differently.
That suggests searching over states instead of nodes. A state is the pair (node, colour of the last edge). There are at most 2n states, and BFS runs over them exactly as it runs over nodes in an ordinary graph. A path to a node is shortest if it is the first time BFS reaches any state of that node, because BFS reaches states in order of their number of edges.
A single "visited" flag per node would be wrong. Suppose node 1 is first reached by a red edge. If that visit marked node 1 as done, a later arrival by a blue edge, which could continue along red edges that the first arrival cannot use, would be thrown away and some answers would come out too large or -1.
The start needs care too: node 0 has no previous edge, so its first edge may be either colour. The solution handles this by seeding the queue with two states, node 0 as if it had been reached by red and node 0 as if it had been reached by blue.
Step by step
- Build the adjacency lists as
adj, whereadj[node][color]is the list of targets of that node's edges of that colour. Colour 0 is red and colour 1 is blue. The array is created withArray.from({length: n}, () => [[], []]), which gives every node its own pair of lists. - Add the red edges. For each
[u, v]inredEdgespushvontoadj[u][0]. Only one direction is stored, because the graph is directed. - Add the blue edges in the same way, onto
adj[u][1]. - Create
distasnew Array(n).fill(-1)and setdist[0] = 0. The value-1is exactly the answer for unreachable nodes, so nodes that are never reached are already correct. - Create
visitedwith one flag per node and colour:Array.from({length: n}, () => [false, false]). Set both flags of node 0 totruewithvisited[0][0] = visited[0][1] = true. - Seed the queue with
[[0, 0, 0], [0, 1, 0]]. Each entry is[node, last colour, distance]. - Loop while the queue is not empty. Every state is queued at most once, so the loop ends.
- Take the front state and unpack it into
u,colorandd.shift()removes from the front, which keeps the queue first-in, first-out. - Flip the colour.
nextColor = 1 - colorturns 0 into 1 and 1 into 0. Loop overadj[u][nextColor], the edges of the colour that the rule now demands. - Skip states already seen. For each target
v, continue only ifvisited[v][nextColor]is false. - Mark the state as seen at once, before it is dequeued, so it cannot enter the queue twice.
- Record the first distance for the node. If
dist[v]is still-1, set it tod + 1. BFS reaches states in order of edge count, so the first value is the smallest and later ones must never overwrite it. - Queue the new state
[v, nextColor, d + 1], one edge farther from node 0. - Return
dist.
The solution in JavaScript
class Solution {
/**
* @param {number} n
* @param {number[][]} redEdges
* @param {number[][]} blueEdges
* @return {number[]}
*/
shortestAlternatingPaths(n, redEdges, blueEdges) {
const adj = Array.from({length: n}, () => [[], []]);
for (const [u, v] of redEdges) {
adj[u][0].push(v);
}
for (const [u, v] of blueEdges) {
adj[u][1].push(v);
}
const dist = new Array(n).fill(-1);
dist[0] = 0;
const visited = Array.from({length: n}, () => [false, false]);
visited[0][0] = visited[0][1] = true;
const queue = [[0, 0, 0], [0, 1, 0]];
while (queue.length > 0) {
const [u, color, d] = queue.shift();
const nextColor = 1 - color;
for (const v of adj[u][nextColor]) {
if (!visited[v][nextColor]) {
visited[v][nextColor] = true;
if (dist[v] === -1) {
dist[v] = d + 1;
}
queue.push([v, nextColor, d + 1]);
}
}
}
return dist;
}
}
JavaScript details worth knowing:
- Destructuring.
for (const [u, v] of redEdges)andconst [u, color, d] = queue.shift()unpack arrays into named variables. They replace index lookups such asstate[2]and make the code easier to read. - Chained assignment.
visited[0][0] = visited[0][1] = trueassigns right to left: the right part setsvisited[0][1]totrueand produces that value, and the left part stores it intovisited[0][0]. - Fresh nested arrays.
Array.from({length: n}, () => [[], []])runs the function once per node.new Array(n).fill([[], []])would share one pair of lists among all nodes. - Arrays as queue entries. A queue entry is a small array. Because
pushandshiftwork on the ends of an array, a plain array serves as a queue.shiftcan be slow on very long arrays, but with 100 nodes there are at most 200 states. - Colours as indexes. Using 0 and 1 for the colours lets
1 - colorflip them and lets the colour be used directly as an array index.
Complexity
Let E be the total number of red and blue edges.
Time: O(n + E). There are at most 2n states, and each is queued at most once. When a state is processed, only the edges of one colour from its node are scanned, so every edge is scanned at most twice overall, once for each colour state of its source.
Space: O(n + E). The adjacency lists hold all edges, and dist, visited and the queue each hold at most O(n) items.
Edge cases and common mistakes
- Node 0 itself.
answer[0]is always0, the empty path. Marking both colours of node 0 as visited keeps its two starting states from being queued again when a cycle leads back to it. - No edges from node 0. Every other node gets
-1. Forn = 3with onlyredEdges = [[1, 2]], the answer is[0, -1, -1]. - Two same-colour edges in a row. Nodes reachable only that way get
-1, as node 2 does in the first example. - Parallel edges and self-edges. Repeated edges just appear twice in a list and are skipped the second time by the visited check. A self-edge leads back to a state that is either unvisited, in which case it is a legitimate longer route, or visited. Neither case causes trouble.
- One visited flag per node. This wrongly discards the second arrival colour, and answers can be too large.
- Marking states on dequeue. The same state could then be queued many times by different predecessors, wasting work.
- Overwriting
dist. Without the=== -1test, a later arrival at the node through the other colour, which is never shorter, would replace the shortest distance.
Testing
n = 3,redEdges = [[0, 1], [1, 2]],blueEdges = []gives[0, 1, -1].n = 3,redEdges = [[0, 1]],blueEdges = [[2, 1], [1, 2]]gives[0, 1, 2].n = 3,redEdges = [[0, 1], [0, 2]],blueEdges = [[1, 0]]gives[0, 1, 1].
