Shortest Path with Alternating Colors - Problem

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] = [a_i, b_i] indicates that there is a directed red edge from node a_i to node b_i in the graph
  • blueEdges[j] = [u_j, v_j] indicates that there is a directed blue edge from node u_j to node v_j in 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.

Input & Output

Example 1 — Basic Alternating Path
$ Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []
Output: [0,1,-1]
💡 Note: From node 0: reach node 1 via red edge (distance 1), cannot reach node 2 (would need blue edge after red, but no blue edges exist)
Example 2 — Multiple Alternating Paths
$ Input: n = 3, redEdges = [[0,1]], blueEdges = [[1,2]]
Output: [0,1,2]
💡 Note: From node 0: reach node 1 via red edge (distance 1), reach node 2 via red then blue edge (distance 2, colors alternate properly)
Example 3 — Complex Graph with Multiple Options
$ Input: n = 3, redEdges = [[0,1],[0,2]], blueEdges = [[1,0]]
Output: [0,1,2]
💡 Note: From node 0: direct red edges to nodes 1 and 2 (both distance 1). The blue edge from 1 to 0 doesn't help reach new nodes.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ redEdges.length, blueEdges.length ≤ 400
  • redEdges[i].length == blueEdges[j].length == 2
  • 0 ≤ ai, bi, uj, vj < n

Visualization

Tap to expand
Shortest Path with Alternating Colors012RedBlueResult Array[0,1,2]Start: dist 0Red path: dist 1Alternating: dist 2Path 0→1→2 alternates colors: Red then BlueEach element shows shortest alternating path from node 0
Understanding the Visualization
1
Input Graph
Directed graph with red and blue edges
2
Alternating Constraint
Path colors must alternate: red→blue→red or blue→red→blue
3
Output Array
Shortest distance from node 0 to each node, or -1 if impossible
Key Takeaway
🎯 Key Insight: Use BFS with state (node, last_color) to track alternating constraint while finding shortest paths
Asked in
Google 15 Facebook 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen