Shortest Path with Alternating Colors

MediumGraphsbfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A directed graph has n nodes labeled 0 to n - 1. Every edge is either red or blue: redEdges[i] = [a, b] is a red edge from a to b, and blueEdges[j] = [u, v] is a blue edge from u to v. The graph may contain self-loops and may have a red and a blue edge between the same pair of nodes. Return an array answer of length n where answer[x] is the number of edges on the shortest path from node 0 to node x whose edge colors strictly alternate (no two consecutive edges share a color). The path may start with either color. If no such path exists, answer[x] is -1. answer[0] is always 0.

Examples

Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []
Output: [0,1,-1]
Node 1 is one red edge away. Reaching node 2 would need two red edges in a row, which is not allowed.
Input: n = 3, redEdges = [[0,1]], blueEdges = [[1,2]]
Output: [0,1,2]
Red `0 -> 1`, then blue `1 -> 2`, gives lengths `1` and `2`.

Constraints

  • 1 <= n <= 100
  • 0 <= redEdges.length, blueEdges.length <= 400
  • `redEdges[i].length == blueEdges[j].length == 2`
  • 0 <= a, b, u, v < n

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bfs problems