The Largest Color Value in a Directed Graph is a complex graph problem that combines traversal with optimization. You are given a directed graph where each node is assigned a color (represented by a lowercase letter). A path's "color value" is defined as the maximum number of nodes of the same color along that path. Your task is to find the maximum color value among all possible paths in the graph. If the graph contains a cycle, the color value is considered infinite (or technically, you return -1 because a path can go around a cycle forever).
This Hash Table, Graph, Topological Sort coding problem is a frequent "Hard" level question at Google and Meta. It tests whether a candidate can detect cycles in a directed graph and perform efficient dynamic programming on a Directed Acyclic Graph (DAG). It requires managing a 2D state (nodes colors) and understanding that a path's color frequency can be computed by building upon the frequencies of its predecessors.
The solution uses Kahn’s Algorithm for Topological Sort combined with Dynamic Programming.
dp[u][char] be the maximum count of char on any path ending at node u.(u, v), for every color c, we update: dp[v][c] = max(dp[v][c], dp[u][c]).dp[v] with all its predecessors, we increment dp[v][color_of_v]. The overall answer is the maximum value in the entire dp table.Suppose we have A -> B -> C and colors are A: 'r', B: 'g', C: 'r'.
dp[A]['r'] = 1, all others 0.A -> B: dp[B]['r'] = max(0, 1) = 1. Then increment dp[B]['g'] to 1.B -> C: dp[C]['r'] = max(0, 1) = 1, dp[C]['g'] = max(0, 1) = 1. Then increment dp[C]['r'] to 2.
The maximum color value is 2 (for color 'r').Whenever you see "maximum value along a path" in a directed graph, think: "Is this a DAG?" if yes, Topological Sort + DP is your go-to strategy. If cycles are possible, cycle detection (using in-degrees or DFS coloring) is the first mandatory step.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Cat and Mouse | Hard | Solve | |
| Count Visited Nodes in a Directed Graph | Hard | Solve | |
| Parallel Courses III | Hard | Solve | |
| Minimum Cost to Split an Array | Hard | Solve | |
| Cat and Mouse II | Hard | Solve |