Skip to content

Latest commit

 

History

History
125 lines (93 loc) · 8.06 KB

File metadata and controls

125 lines (93 loc) · 8.06 KB

Shortest Path with Alternating Colors - Leetcode 1129

Disclaimer: This is a personal summary and interpretation based on a YouTube video. It is not official material and not endorsed by the original creator. All rights remain with the respective creators.

This document summarizes the key takeaways from the video. I highly recommend watching the full video for visual context and coding demonstrations.

Before You Get Started

  • I summarize key points to help you learn and review quickly.
  • Simply click on Ask AI links to dive into any topic you want.

AI-Powered buttons

Teach Me: 5 Years Old | Beginner | Intermediate | Advanced | (reset auto redirect)

Learn Differently: Analogy | Storytelling | Cheatsheet | Mindmap | Flashcards | Practical Projects | Code Examples | Common Mistakes

Check Understanding: Generate Quiz | Interview Me | Refactor Challenge | Assessment Rubric | Next Steps

Problem Description

Rust handles memory safety by... wait, no—this is about a graph problem. Nodes are numbered from 0 to n-1 in a directed graph with edges colored red or blue. Start at node 0 and find the shortest path to every other node where edge colors alternate. Return an array with these lengths; use -1 if no such path exists.

Key takeaway: Paths must alternate colors, like blue-red-blue or red-blue-red, and we're dealing with directed edges.

Ask AI: Problem Description

Example Walkthrough

In a simple graph with nodes 0, 1, 2, and edges like 0->1 (blue) and 1->2 (red), the path 0-1-2 alternates colors, so lengths are [0, 1, 2]. If 1->2 is blue instead, it doesn't alternate, so [0, 1, -1]. If edges don't alternate, return -1 for unreachable nodes under the rule.

Key example: Adding more edges shows how alternating enforces the constraint, and single-edge paths always qualify since no prior color.

Ask AI: Example Walkthrough

Approach: BFS with Color Tracking

Use BFS starting from node 0. Track the previous edge color to ensure alternation. Visit each node potentially twice—once via red incoming edge, once via blue—to explore all possibilities. Use a visited set for (node, color) pairs to avoid cycles while allowing multiple paths.

Key takeaway: By handling both starting colors (red or blue from 0) simultaneously in one BFS, you cover all alternating paths. First visit to a node sets the shortest length.

Ask AI: BFS Approach

Building the Graph

Convert red_edges and blue_edges lists into adjacency maps: one for red, one for blue. For each edge [src, dest], append dest to src's list in the corresponding color map.

Key code snippet:

red = defaultdict(list)
blue = defaultdict(list)
for src, dest in red_edges:
    red[src].append(dest)
for src, dest in blue_edges:
    blue[src].append(dest)

Ask AI: Building the Graph

Initializing BFS Components

Initialize answer array with -1s. Queue starts with [0, 0, None] (node, length, prev_color). Visited set adds (0, None). This allows exploring both red and blue from start without restriction.

Key takeaway: None for initial color lets you branch into both colors.

Ask AI: BFS Initialization

BFS Execution

While queue not empty, dequeue node, length, prev_color. If answer[node] == -1, set it to length. Then, if prev_color != 'red', enqueue blue neighbors with 'blue' color and length+1, if not visited. If prev_color != 'blue', do the same for red neighbors.

Key code snippet:

while queue:
    node, length, edge_color = queue.popleft()
    if answer[node] == -1:
        answer[node] = length
    if edge_color != "red":
        for nei in blue[node]:
            if (nei, "blue") not in visit:
                visit.add((nei, "blue"))
                queue.append([nei, length + 1, "blue"])
    if edge_color != "blue":
        for nei in red[node]:
            if (nei, "red") not in visit:
                visit.add((nei, "red"))
                queue.append([nei, length + 1, "red"])

Ask AI: BFS Execution

Time and Space Complexity

Time is O(n + e) since BFS visits each node and edge, effectively twice per color but still linear. Space is O(n) for visited set and queue.

Key takeaway: Multiplying by constant (like 2 for colors) doesn't change Big O.

Ask AI: Complexity Analysis


About the summarizer

I'm Ali Sol, a Backend Developer. Learn more: