Problem 1129

Abstract / Summary

Find the shortest path in a graph where steps must switch between two colors and you start at a given node and target color.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
49 lines | 1250 bytes | submitted October 2, 2023 | GitHub   tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 48% (300k+ submissions).

Typical patterns to solve this problem:
  • Breadth First Search
  • Graph Theory
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 red and blue are 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/seenBlue checks 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 redEdges is 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, and nextBlue enables O(1) membership tests and eliminates duplicate nodes within the same BFS layer, reducing unnecessary iterations.
  • Separate visited sets per color: By distinguishing seenRed from seenBlue, 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] and nextRed |= 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.00 | σ = 1.33

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
23 links | 12 authors | 7 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

14 solutions   October 2, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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