#1857
Largest Color Value in a Directed Graph
HardHash TableStringDynamic ProgrammingGraph TheoryTopological SortMemoizationCountingGraph TraversalDynamic ProgrammingTopological Sort
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + m)Space O(n)
Using topological sorting allows us to process nodes in a way that ensures we handle all dependencies before a node is processed. This helps us avoid cycles and efficiently calculate the maximum color value along valid paths.
⚙️
Algorithm
4 steps- 1Step 1: Build the graph and calculate in-degrees for each node.
- 2Step 2: Perform a topological sort using Kahn's algorithm, maintaining a queue of nodes with zero in-degrees.
- 3Step 3: For each node processed, update the color counts for its neighbors based on the current node's counts.
- 4Step 4: Track the maximum color value encountered during the updates.
solution.py27 lines
1def largestColorValue(colors, edges):
2 from collections import defaultdict, deque
3 n = len(colors)
4 graph = defaultdict(list)
5 in_degree = [0] * n
6
7 for u, v in edges:
8 graph[u].append(v)
9 in_degree[v] += 1
10
11 queue = deque([i for i in range(n) if in_degree[i] == 0])
12 color_count = [[0] * 26 for _ in range(n)]
13 max_color_value = 0
14
15 while queue:
16 node = queue.popleft()
17 color_count[node][ord(colors[node]) - ord('a')] += 1
18 max_color_value = max(max_color_value, max(color_count[node]))
19
20 for neighbor in graph[node]:
21 for c in range(26):
22 color_count[neighbor][c] = max(color_count[neighbor][c], color_count[node][c])
23 in_degree[neighbor] -= 1
24 if in_degree[neighbor] == 0:
25 queue.append(neighbor)
26
27 return max_color_value if all(d == 0 for d in in_degree) else -1ℹ
Complexity note: The complexity is O(n + m) because we traverse each node and edge once during the topological sort and color counting.
- 1Topological sorting is essential for processing nodes in a directed graph without cycles.
- 2Dynamic programming can help track color counts efficiently across paths.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.