Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find largest color value in a directed graph in Python
Suppose we have a directed graph with n colored nodes and m different edges. The nodes are numbered from 0 to n-1. We have a string col with lowercase letters, where col[i] represents the color of the ith node in this graph (0-indexed). We also have an edge list where edges[j] = (u, v) represents there is an edge between u and v.
A valid path in the graph is a sequence of nodes xi for all i from 1 to k, such that there is a directed edge from xi to xi+1. The color value of the path is the most frequent node color of that path. We have to find the largest color value of any valid path in that graph. If there is a cycle in the graph then return -1.
Problem Example
If the input is like col = "aabada" and edges = [(0,1),(1,4),(1,2),(2,3),(3,5),(4,5)] ?
The output will be 4 because the path 0 ? 1 ? 2 ? 3 ? 5 has the longest sequence with color 'a' appearing 4 times.
Algorithm Approach
We use topological sorting with dynamic programming to solve this problem ?
- Build adjacency list and calculate in-degrees
- Use DP array to track maximum count of each color for each node
- Process nodes in topological order using Kahn's algorithm
- If we can't visit all nodes, there's a cycle (return -1)
- Return the maximum color count across all nodes
Implementation
from collections import defaultdict
def solve(col, edges):
n = len(col)
graph = defaultdict(list)
indegree = defaultdict(int)
# Build graph and calculate in-degrees
for u, v in edges:
graph[u].append(v)
indegree[v] += 1
queue = []
dp = [[0] * 26 for _ in range(n)]
colorvalues = [ord(c) - ord("a") for c in col]
# Initialize nodes with in-degree 0
for u in range(n):
if u not in indegree:
queue.append(u)
dp[u][colorvalues[u]] = 1
visited = 0
# Process nodes in topological order
while queue:
u = queue.pop(0) # Use FIFO for proper topological order
visited += 1
for v in graph[u]:
# Update DP values for all colors
for c in range(26):
dp[v][c] = max(dp[v][c], dp[u][c] + (c == colorvalues[v]))
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
del indegree[v]
# Check for cycle
if visited < n:
return -1
# Return maximum color count
return max(max(x) for x in dp)
# Test the solution
col = "aabada"
edges = [(0,1),(1,4),(1,2),(2,3),(3,5),(4,5)]
print(solve(col, edges))
4
How It Works
The algorithm works by maintaining a DP table where dp[node][color] represents the maximum count of a specific color ending at that node. For each node processed in topological order, we update all its neighbors by propagating the color counts and incrementing the count if the neighbor has the same color.
Key Points
- Time Complexity: O(n × 26 + m) where n is nodes and m is edges
- Space Complexity: O(n × 26) for the DP table
- Cycle Detection: If we can't visit all nodes, a cycle exists
- Topological Sort: Ensures we process dependencies in correct order
Conclusion
This solution uses topological sorting with dynamic programming to find the largest color value in any valid path. The approach efficiently handles cycle detection and tracks color frequencies across all possible paths.
