 All Problems
Largest Color Value in a Directed Graph
hard
topological sort
graph
dynamic programming
google
amazon
uber

There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n-1. You are given a string colors where colors[i] is a lowercase letter representing the color of node i, and a 2D array edges.

A valid path in the graph is a sequence of nodes where there is a directed edge from each node to the next. The color value of the path is the number of nodes with the most frequent color.

Return the largest color value of any valid path, or -1 if there is a cycle.

Example 1:

Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
Output: 3  (path 0->2->3->4 has color 'a' appearing 3 times)

Constraints:

  • 1 <= n <= 10^5
  • 0 <= m <= 10^5
Run to check your code against the sample cases, or submit to run every case