Shortest Route Alternating Between Red and Blue Links
Last updated: November 29, 2026
Quick Overview
A directed graph has red edges and blue edges. For every node, return the length of the shortest path from node 0 whose edge colors alternate, or -1 if no such path exists.
0
0
0 solved
A directed graph has red edges and blue edges. For every node, return the length of the shortest path from node 0 whose edge colors alternate, or -1 if no such path exists.
A technical screen question about BFS with state, for example routing that must alternate between two transport modes or two carriers. The interviewer wants you to notice that a node reached via a red edge and the same node reached via a blue edge are different states.
What the Interviewer Expects
- Expand state to (node, color of last edge)
- Seed BFS with node 0 in both color states
- Follow only edges of the opposite color
- Take the minimum over both states per node
- Explain why plain per-node visited marks give wrong answers
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What if there are three colors that must cycle in order?
- What if edges have weights?
- Return the path itself for a given node.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
n,red_edges,blue_edgesas directed pairs. - A valid path alternates colors; either color can be first.
- Output: array
ans[i]of shortest valid path lengths,ans[0] = 0....
High-Level Design
Visiting node v after a red edge allows only blue next, and after a blue edge only red. These are different futures, so a single visited flag per node is wrong: the first arrival might be via the co...