Close
Topic list
Shortest alternate colored path
MEDIUM
20 mins
Graph
Topics (Covered in this problem)
Problem solved
Skill meter
Graph
-
-
Other topics
Problem solved
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

# Shortest alternate colored path

Contributed by
Mutiur Rehman khan
Medium
0/80
Avg time to solve 20 mins
Success Rate 80 %
Share

## Problem Statement

#### Your task is to compute an array ‘answer’ of size ‘N’, where ‘answer[i]’ stores the length of the shortest path from node ‘0’ to node ‘i’ such that the edges along the path have alternate colors. If there is no such path from node ‘0’ to ‘i’, then ‘answer[i] = -1’.

##### Example:
``````N = 4, redEdges = [[0, 1], [2, 3]], blueEdges = [[1, 2], [1, 3]]
``````

``````The shortest paths for each node from node ‘0’ are:
1: 0->1         Length: 1
2: 0->1->2      Length: 2
3: 0->1->3      Length: 2
So, the ‘answer’ array will be: [0, 1, 2, 2].
``````
##### Note:
``````1. The given graph could be a disconnected graph.

2. Any two nodes ‘i’ and ‘j’ can have at most one red edge from ‘i’ to ‘j’ and at most one blue edge from ‘i’ to ‘j’.
``````
Detailed explanation ( Input/output format, Notes, Constraints, Images )

#### Sample input 1:

``````2
4 2 2
0 1
1 3
1 1
1 2
4 2 2
0 1
1 3
0 2
2 3
``````

#### Sample output 1:

``````0 1 2 3
0 1 1 -1
``````

#### Explanation of sample input 1:

``````Test Case 1:

n = 4, redEdges = [[0,1], [1, 3]], blueEdges = [[1, 1], [1, 2]]
``````

``````The shortest paths for each node from node ‘0’ are:
1: 0->1          Length: 1
2: 0->1->2      Length: 2
3: 0->1->1->3   Length: 3
So, the ‘answer’ array will be: [0, 1, 2, 3].

Test Case 2:

n = 4, redEdges = [[0, 1], [1, 3]], blueEdges = [[0, 2], [2, 3]]
``````

``````The shortest paths for each node from node ‘0’ are:
1: 0->1     Length: 1
2: 0->2     Length: 1
3: No valid path available.
So, the ‘answer’ array will be: [0, 1, 1, -1].
``````

#### Sample input 2:

``````2
3 1 1
2 1
1 0
3 1 2
1 0
0 1
0 2
``````

#### Sample output 2:

``````0 -1 -1
0 1 1
``````
Auto
Console