Largest Color Value in a Directed Graph - Problem
Graph Coloring Path Challenge: You're given a directed graph where each node has a specific color (represented by lowercase letters). Your mission is to find the most dominant color along any valid path in the graph.

The Problem: Given n colored nodes numbered 0 to n-1 and a string colors where colors[i] represents the color of node i, plus an array of directed edges, you need to:

1. Find all valid paths in the graph (following directed edges)
2. For each path, count the frequency of each color
3. The "color value" of a path is the count of its most frequent color
4. Return the maximum color value among all paths

Important: If the graph contains a cycle, return -1 (since cycles would allow infinite path lengths).

Example: If a path goes through nodes with colors "abbac", the most frequent color is 'a' (appears 2 times), so this path has color value 2.

Input & Output

example_1.py — Basic Path
$ Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
Output: 3
💡 Note: The path 0 -> 2 -> 3 -> 4 produces the sequence "acaa". Color 'a' appears 3 times, which is the maximum.
example_2.py — Multiple Paths
$ Input: colors = "a", edges = [[0,0]]
Output: -1
💡 Note: There is a cycle from 0 to 0, so we return -1.
example_3.py — Single Node
$ Input: colors = "abc", edges = []
Output: 1
💡 Note: No edges means each node forms its own path. The maximum color value is 1 (any single node).

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ m ≤ 105
  • edges[i].length == 2
  • 0 ≤ ai, bi ≤ n - 1
  • ai ≠ bi
  • colors consists of lowercase English letters

Visualization

Tap to expand
Largest Color Value in a Directed Graph INPUT 0:a 1:b 2:a 3:c 4:a colors = "abaca" edges = [[0,1],[0,2],[2,3],[3,4]] ALGORITHM (DP) 1 Detect Cycles Use Kahn's algo (in-degree) 2 Topological Sort Process nodes in order 3 DP State dp[node][color] = max count 4 Propagate Values Update child with parent max DP Table (path: 0-2-3-4) Node a b c 0 1 0 0 2 2 0 0 3 2 0 1 4 3 0 1 Max = 3 (color 'a') FINAL RESULT Optimal Path Found a a c a Path: 0 --> 2 --> 3 --> 4 Colors: a, a, c, a Output: 3 OK - Max color 'a' = 3 Key Insight: Use DP with topological sort: dp[node][color] tracks the maximum count of each color on any path ending at that node. For each edge (u,v), update: dp[v][c] = max(dp[v][c], dp[u][c]). Then add 1 for the current node's color. Cycle detection via topological sort returns -1 if cycle exists. TutorialsPoint - Largest Color Value in a Directed Graph | Dynamic Programming Approach
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
31.8K Views
Medium Frequency
~25 min Avg. Time
982 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen