Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Home
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets

Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Back to Problems

1129. Shortest Path with Alternating Colors

Medium47.1% Acceptance
Breadth-First SearchGraph
Asked by:
B
Bloomberg
Google
ProblemHints (1)Solutions (4)VideosCompanies (5)Notes

Problem Statement

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] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and
  • blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj 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.

Example 1:

Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []
Output: [0,1,-1]

Example 2:

Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]
Output: [0,1,-1]

Constraints:

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

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
G
W
Wish
L
LinkedIn
A
Amazon

Approach

In #1129 Shortest Path with Alternating Colors, the key challenge is ensuring that consecutive edges in a path alternate between red and blue. A natural way to explore shortest paths in an unweighted graph is Breadth-First Search (BFS), but here we must track the color of the last edge used.

The idea is to represent each state as (node, lastColor). From a node reached via a red edge, you only explore blue edges next, and vice versa. By pushing these states into a BFS queue, you ensure that the first time a node is reached with a valid color sequence corresponds to the shortest alternating path.

To avoid revisiting the same state, maintain a visited[node][color] structure. This ensures the traversal remains efficient while exploring valid alternating transitions. Since BFS processes nodes level by level, it naturally yields the minimum number of steps required to reach each node with alternating colors.

Time Complexity: O(n + e). Space Complexity: O(n + e) due to adjacency lists, queue states, and visited tracking.

Complexity

ApproachTime ComplexitySpace Complexity
Breadth-First Search with color state trackingO(n + e)O(n + e)

Video Solution Available

NeetCodeIO

View all video solutions

Problem Hints

Use these hints if you're stuck. Try solving on your own first.

1
Hint 1

Do a breadth-first search, where the "nodes" are actually (Node, color of last edge taken).

Ready to see the solutions?View Solutions

Solutions (4)

BFS with State Tracking

Use a Breadth-First Search (BFS) to traverse the graph, keeping track of the last edge color used (red or blue). This can be done using a queue where each element is a tuple containing the current node, distance traveled, and the color of the edge used to arrive at this node. We need two visited arrays to track if a node has been visited with a red edge or a blue edge to avoid re-processing.

Time Complexity: O(n + redEdges.length + blueEdges.length) - This accounts for the BFS traversal and the construction of adjacency lists.
Space Complexity: O(n) - This is the space required for visited sets and the BFS queue.

PythonJavaScript
1from collections import deque
2
3class Solution:
4    def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
5        adj_red = [[] for _ in range(n)]
6        adj_blue = [[] for _ in range(n)]
7        for u, v in redEdges:
8            adj_red[u].append(v)
9        for u, v in blueEdges:
10            adj_blue[u].append(v)
11
12        answer = [-1] * n
13        answer[0] = 0
14        queue = deque([(0, 0, None)])
15        visited_red = set()
16        visited_blue = set()
17
18        while queue:
19            node, dist, last_color = queue.popleft()
20
21            if last_color != 'red':
22                for nei in adj_red[node]:
23                    if nei not in visited_red:
24                        visited_red.add(nei)
25                        if answer[nei] == -1:
26                            answer[nei] = dist + 1
27                        queue.append((nei, dist + 1, 'red'))
28
29            if last_color != 'blue':
30                for nei in adj_blue[node]:
31                    if nei not in visited_blue:
32                        visited_blue.add(nei)
33                        if answer[nei] == -1:
34                            answer[nei] = dist + 1
35                        queue.append((nei, dist + 1, 'blue'))
36
37        return answer

Explanation

The solution first constructs adjacency lists for red and blue edges. A deque is used for BFS which starts from node 0 with a distance of 0. For each node, it checks the next possible nodes via red or blue edges, ensuring no repeated visits are made using the same edge color. It updates the shortest distance for each node when it is first reached, ensuring paths alternate between red and blue.

Layered BFS with Two Queues

This approach involves using two separate BFS queues to handle paths starting with red and blue edges. By maintaining distinct queues for red and blue path exploration, the solution ensures color alternation by construction, processing nodes layer by layer from each starting color queue separately.

Time Complexity: O(n + redEdges.length + blueEdges.length) - The layer processing replicates BFS traversal cost.
Space Complexity: O(n) - Needed for separate visitation states and queue management.

JavaC++
1import java.util.*;
2
3





Video Solutions

Watch expert explanations and walkthroughs

Shortest Path with Alternating Colors - Leetcode 1129 - Python

NeetCodeIO
13:4315,052 views

Asked By Companies

5 companies
B
Bloomberg
G
Google
W
Wish
L
LinkedIn
A
Amazon

Prepare for Interviews

Practice problems asked by these companies to ace your technical interviews.

Explore More Problems

Notes

Personal Notes

Jot down your thoughts, approach, and key learnings

0 characters

Similar Problems

Related Topics

Breadth-First SearchGraph

Problem Stats

Acceptance Rate47.1%
DifficultyMedium
Companies5

Practice on LeetCode

Solve with full IDE support and test cases

Solve Now

Frequently Asked Questions

Why do we track edge colors in the BFS state?

Tracking the previous edge color ensures that the next edge chosen alternates correctly. Without storing this information, the algorithm might incorrectly traverse two edges of the same color in sequence.

Is Shortest Path with Alternating Colors asked in FAANG interviews?

Yes, graph traversal problems like this frequently appear in technical interviews at large tech companies. Variations of BFS with state tracking are commonly used to test problem-solving and graph modeling skills.

What data structure is best for Shortest Path with Alternating Colors?

A queue is used for BFS traversal, along with adjacency lists to represent red and blue edges. Additionally, a visited structure like visited[node][color] helps avoid revisiting the same node with the same previous edge color.

What is the optimal approach for Shortest Path with Alternating Colors?

The optimal approach uses Breadth-First Search while tracking the color of the last edge used. Each state is represented as (node, lastColor), ensuring the next step uses the opposite color. This guarantees the shortest alternating path in an unweighted graph.

class
Solution
{
4
public
int
[
]
shortestAlternatingPaths
(
int
n
,
int
[
]
[
]
redEdges
,
int
[
]
[
]
blueEdges
)
{
5
List
<
Integer
>
[
]
redAdj
=
new
ArrayList
[
n
]
;
6
List
<
Integer
>
[
]
blueAdj
=
new
ArrayList
[
n
]
;
7
for
(
int
i
=
0
;
i
<
n
;
i
++
)
{
8
redAdj
[
i
]
=
new
ArrayList
<
>
(
)
;
9
blueAdj
[
i
]
=
new
ArrayList
<
>
(
)
;
10
}
11
for
(
int
[
]
edge
:
redEdges
)
redAdj
[
edge
[
0
]
]
.
add
(
edge
[
1
]
)
;
12
for
(
int
[
]
edge
:
blueEdges
)
blueAdj
[
edge
[
0
]
]
.
add
(
edge
[
1
]
)
;
13
14
int
[
]
answer
=
new
int
[
n
]
;
15
Arrays
.
fill
(
answer
,
-
1
)
;
16
answer
[
0
]
=
0
;
17
18
Queue
<
int
[
]
>
queueRed
=
new
LinkedList
<
>
(
)
;
19
Queue
<
int
[
]
>
queueBlue
=
new
LinkedList
<
>
(
)
;
20
boolean
[
]
visitedRed
=
new
boolean
[
n
]
;
21
boolean
[
]
visitedBlue
=
new
boolean
[
n
]
;
22
23
queueRed
.
offer
(
new
int
[
]
{
0
,
0
}
)
;
24
queueBlue
.
offer
(
new
int
[
]
{
0
,
0
}
)
;
25
26
while
(
!
queueRed
.
isEmpty
(
)
||
!
queueBlue
.
isEmpty
(
)
)
{
27
if
(
!
queueRed
.
isEmpty
(
)
)
{
28
int
size
=
queueRed
.
size
(
)
;
29
for
(
int
i
=
0
;
i
<
size
;
i
++
)
{
30
int
[
]
curr
=
queueRed
.
poll
(
)
;
31
int
node
=
curr
[
0
]
;
32
int
dist
=
curr
[
1
]
;
33
for
(
int
neighbor
:
blueAdj
[
node
]
)
{
34
if
(
!
visitedBlue
[
neighbor
]
)
{
35
visitedBlue
[
neighbor
]
=
true
;
36
answer
[
neighbor
]
=
answer
[
neighbor
]
==
-
1
?
dist
+
1
:
Math
.
min
(
answer
[
neighbor
]
,
dist
+
1
)
;
37
queueBlue
.
offer
(
new
int
[
]
{
neighbor
,
dist
+
1
}
)
;
38
}
39
}
40
}
41
}
42
43
if
(
!
queueBlue
.
isEmpty
(
)
)
{
44
int
size
=
queueBlue
.
size
(
)
;
45
for
(
int
i
=
0
;
i
<
size
;
i
++
)
{
46
int
[
]
curr
=
queueBlue
.
poll
(
)
;
47
int
node
=
curr
[
0
]
;
48
int
dist
=
curr
[
1
]
;
49
for
(
int
neighbor
:
redAdj
[
node
]
)
{
50
if
(
!
visitedRed
[
neighbor
]
)
{
51
visitedRed
[
neighbor
]
=
true
;
52
answer
[
neighbor
]
=
answer
[
neighbor
]
==
-
1
?
dist
+
1
:
Math
.
min
(
answer
[
neighbor
]
,
dist
+
1
)
;
53
queueRed
.
offer
(
new
int
[
]
{
neighbor
,
dist
+
1
}
)
;
54
}
55
}
56
}
57
}
58
}
59
60
return
answer
;
61
}
62
}

Explanation

This Java implementation operates with two BFS queues dedicated for red and blue starting paths. The strategy processes node connections based on the opposite color adjacency list, alternatively updating shortest paths. Each queue contributes towards a layer of nodes processed, ensuring paths alternate colors efficiently with minimized total distances computed.

Clone GraphMedium
Course ScheduleMedium
Course Schedule IIMedium
Graph Valid TreeMedium
More similar problems