Python 1129.py
class Solution:
def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
result = [ -1 ] * n
result[0] = 0
r = defaultdict(set)
for src, dst in redEdges:
r[src].add(dst)
b = defaultdict(set)
for src, dst in blueEdges:
b[src].add(dst)
red = r[0]
blue = b[0]
seenRed = set()
seenBlue = set()
steps = 1
while red or blue:
nextRed = set()
nextBlue = set()
for current in red:
if current in seenRed:
continue
seenRed.add(current)
if result[current] == -1:
result[current] = steps
nextBlue |= b[current]
for current in blue:
if current in seenBlue:
continue
seenBlue.add(current)
if result[current] == -1:
result[current] = steps
nextRed |= r[current]
steps += 1
red = nextRed
blue = nextBlue
return result
Difficulty
and has an acceptance rate of about 48% (300k+ submissions).
Typical patterns to solve this problem:
- Breadth First Search
- Graph Theory
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation computes the shortest path lengths from node 0 to every other node in a directed graph where edges are colored red or blue. A valid path must alternate colors at each step. The algorithm performs a breadth-first search (BFS) that expands simultaneously from the current frontier of red-colored edges and blue-colored edges, guaranteeing that the first time a node is reached its distance is minimal under the alternating-color constraint.
Data Structures
The code uses three primary containers:
result = [ -1 ] * n
r = defaultdict(set)
b = defaultdict(set)
result stores the distance to each node, initialized to -1 (unreachable) except for the source node 0.
r and b map a source node to the set of its red or blue neighbours respectively. The use of defaultdict(set) provides O(1) insertion and lookup while automatically handling missing keys.
Two additional sets track nodes that have already been visited via a red edge or a blue edge:
seenRed = set()
seenBlue = set()
These sets prevent revisiting a node through the same color, which would otherwise create cycles and redundant work.
Initialization
The adjacency maps are populated by iterating over the input edge lists:
for src, dst in redEdges:
r[src].add(dst)
for src, dst in blueEdges:
b[src].add(dst)
The initial frontiers consist of the neighbours reachable from node 0 using a single red edge and a single blue edge:
red = r[0]
blue = b[0]
The distance counter starts at one because the first expansion represents paths of length 1.
BFS Loop
The core of the algorithm is a loop that continues while there are nodes reachable via either color:
steps = 1
while red or blue:
nextRed = set()
nextBlue = set()
for current in red:
if current in seenRed:
continue
seenRed.add(current)
if result[current] == -1:
result[current] = steps
nextBlue |= b[current]
for current in blue:
if current in seenBlue:
continue
seenBlue.add(current)
if result[current] == -1:
result[current] = steps
nextRed |= r[current]
steps += 1
red = nextRed
blue = nextBlue
The loop processes the current red frontier first. For each node, it checks whether the node has already been visited via a red edge; if not, it records the distance and adds all blue neighbours of that node to the next blue frontier. The blue frontier is handled symmetrically, adding red neighbours to the next red frontier. The steps counter is incremented after both frontiers have been processed, ensuring that all nodes discovered in the same BFS layer receive the same distance value.
Result Construction
After the BFS terminates, the result list contains the shortest alternating-color distances for all nodes, with -1 indicating that a node cannot be reached under the alternating constraint. The final line simply returns this list:
return result
Edge Cases Handled
The algorithm gracefully handles several edge conditions:
- No outgoing edges from the source: If both
redandblueare empty initially, the while loop never executes and the result remains[0, -1, -1, …], correctly indicating that only the source is reachable. - Self-loops: A self-loop appears as an edge from a node to itself. When such an edge is encountered, the node is added to the opposite-color frontier, but the
seenRed/seenBluechecks prevent infinite repetition, and the distance is recorded only once. - Multiple edges of the same color between the same pair: Because adjacency lists are stored as sets, duplicate edges are collapsed, avoiding redundant processing.
- Disconnected components: Nodes that belong to a component without any path from node 0 never enter either frontier, leaving their entries as -1.
- Graphs with only one color: If
redEdgesis empty, the red adjacency map stays empty, and the BFS proceeds solely through blue edges, still respecting the alternating rule because the red frontier will be empty after the first iteration.
Performance Optimizations
Several design choices contribute to efficient execution:
- Set-based frontiers: Using sets for
red,blue,nextRed, andnextBlueenables O(1) membership tests and eliminates duplicate nodes within the same BFS layer, reducing unnecessary iterations. - Separate visited sets per color: By distinguishing
seenRedfromseenBlue, the algorithm allows a node to be revisited if it can be reached via a different color, which is essential for alternating paths while still preventing redundant work. - Bitwise-or assignment for frontier expansion: The statements
nextBlue |= b[current]andnextRed |= r[current]merge neighbour sets in a single operation, avoiding explicit loops over neighbours and minimizing Python overhead. - Early distance assignment: The distance for a node is set the first time it is encountered, and subsequent encounters are ignored because
result[current]is no longer -1. This avoids overwriting a correct minimal distance. - Avoidance of explicit queue structures: Traditional BFS uses a queue; here, the algorithm swaps whole frontier sets each iteration, which reduces the number of push/pop operations and leverages Python’s efficient set operations.
Overall, the code delivers a concise and effective solution for computing shortest alternating paths, leveraging set semantics and careful bookkeeping to ensure correctness and performance.
ELI5 - Simplified Explanation
Imagine you have a map of different houses connected by colorful paths. Some paths are red and some are blue. You start at the very first house and want to visit all the other houses by walking along the paths. The rule is that you must change the color of the path every time you move to a new house. If you take a red path, the next one must be blue, and if you take a blue path, the next one must be red.
This code acts like a little explorer. It first looks at all the houses you can reach from the start using a red path and all the houses you can reach using a blue path. It keeps track of which houses have been visited with a certain color so that you do not walk in circles. It uses two separate lists to remember where you have been, one for when you arrive on a red path and one for when you arrive on a blue path.
As the explorer moves, it counts how many steps it takes to get to each house. If you reach a house for the first time, it writes down that number of steps. It keeps repeating this process, switching colors for every step, until there are no new houses left to explore. If a house is buried in a way that you can never reach it by following the color pattern, the code keeps the number at a special mark to show that the house is unreachable. After traveling through all the possible paths, the final list shows the shortest number of steps needed to reach every house from the start.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | Python | |||||
| leetcode.ca | C++ | Java | Python | Go | TS | |||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 997: Find the Town Judge
- problem 695: Max Area of Island
- problem 797: All Paths From Source to Target
- problem 802: Find Eventual Safe States
- problem 863: All Nodes Distance K in Binary Tree
- problem 934: Shortest Bridge
- problem 1020: Number of Enclaves
- problem 1091: Shortest Path in Binary Matrix
- problem 1306: Jump Game III
- problem 1376: Time Needed to Inform All Employees
- problem 1557: Minimum Number of Vertices to Reach All Nodes
- problem 2038: Remove Colored Pieces if Both Neighbors are the Same Color
- problem 212: Word Search II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality