Shortest Directed Routes With Alternating Edge Colors

Quick Overview

Shortest Directed Routes With Alternating Edge Colors. A directed graph on nodes0 through n-1 has redEdges and blueEdges.

Shortest Directed Routes With Alternating Edge Colors

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem A directed graph on nodes 0 through n-1 has redEdges and blueEdges. Self-loops and parallel edges are allowed. For every node, return the smallest edge count from node 0 along a route whose consecutive edge colors alternate, or -1 if unreachable. The distance from 0 to itself is 0. ```cpp class Solution { public: vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& redEdges, vector<vector<int>>& blueEdges); }; ``` ### Examples **Example 1:** ```text Input: n = 4, redEdges = [[0,1],[2,3]], blueEdges = [[1,2]] Output: [0,1,2,3] Explanation: The chain uses red,blue,red. ``` **Example 2:** ```text Input: n = 3, redEdges = [], blueEdges = [[0,1],[1,2]] Output: [0,1,-1] Explanation: Two successive blue edges cannot form an alternating route. ``` ### Constraints - The graph contains 1 to 100 nodes. - Each color list has 0 to 400 edges; every edge is a pair of labels in `[0,n-1]`. - Self-loops and parallel edges are allowed. ### Contract considerations Edges remain directed, and either color may be used first. ```hint Read the boundary condition Does a single-edge route satisfy alternation regardless of its color, and what distance is required at the start? ``` ### Boundary reminders Edges remain directed, and either color may be used first.

Overview: Shortest Directed Routes With Alternating Edge Colors. A directed graph on nodes0 through n-1 has redEdges and blueEdges.

Google logo
Google
Source window: 0–6 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

A directed graph on nodes 0 through n-1 has redEdges and blueEdges. Self-loops and parallel edges are allowed. For every node, return the smallest edge count from node 0 along a route whose consecutive edge colors alternate, or -1 if unreachable. The distance from 0 to itself is 0.

class Solution {
public:
    vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& redEdges, vector<vector<int>>& blueEdges);
};

Examples

Example 1:

Input: n = 4, redEdges = [[0,1],[2,3]], blueEdges = [[1,2]]
Output: [0,1,2,3]
Explanation: The chain uses red,blue,red.

Example 2:

Input: n = 3, redEdges = [], blueEdges = [[0,1],[1,2]]
Output: [0,1,-1]
Explanation: Two successive blue edges cannot form an alternating route.

Constraints

  • The graph contains 1 to 100 nodes.
  • Each color list has 0 to 400 edges; every edge is a pair of labels in [0,n-1] .
  • Self-loops and parallel edges are allowed.

Contract considerations

Edges remain directed, and either color may be used first.

Boundary reminders

Edges remain directed, and either color may be used first.