#1129

Shortest Path with Alternating Colors

Medium
Breadth-First SearchGraph TheoryGraph TraversalBreadth-First SearchState Management in Graphs
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + e)
Space
O(1)
O(n)
💡

Intuition

Time O(n + e)Space O(n)

The optimal solution uses a breadth-first search (BFS) approach, where we maintain two queues to track the current node and the last edge color used. This allows us to efficiently explore the graph while ensuring that colors alternate, leading to a faster solution.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a graph representation using adjacency lists for both red and blue edges.
  2. 2Step 2: Initialize a queue for BFS, starting from node 0 with both colors and a distance of 0.
  3. 3Step 3: While the queue is not empty, explore neighbors based on the last edge color, updating distances and adding new nodes to the queue.
solution.py23 lines
1# Full working Python code
2from collections import deque
3
4def shortestAlternatingPaths(n, redEdges, blueEdges):
5    graph = {i: {'red': [], 'blue': []} for i in range(n)}
6    for u, v in redEdges:
7        graph[u]['red'].append(v)
8    for u, v in blueEdges:
9        graph[u]['blue'].append(v)
10
11    distances = [-1] * n
12    distances[0] = 0
13    queue = deque([(0, 'red', 0), (0, 'blue', 0)])
14
15    while queue:
16        node, color, dist = queue.popleft()
17        next_color = 'blue' if color == 'red' else 'red'
18        for neighbor in graph[node][next_color]:
19            if distances[neighbor] == -1:
20                distances[neighbor] = dist + 1
21                queue.append((neighbor, next_color, dist + 1))
22
23    return distances

Complexity note: The complexity is O(n + e) where e is the number of edges, as we explore each node and edge once during BFS.

  • 1Use BFS for shortest path problems in graphs.
  • 2Maintain state of the last edge color to ensure alternation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.