Largest Color Value in a Directed Graph

Hard Topics Company Tags

A directed graph has one node for each character in colors. Node i has color colors[i], a lowercase English letter. Each pair [from, to] in edges gives a directed edge.

The color value of a path is the largest number of times a single color occurs among its nodes. A path follows the direction of every edge; a single node is also a path.

Return the greatest color value over all paths. If any part of the graph contains a directed cycle, return -1, even if that cycle is disconnected from other nodes.

Diagram nodes show node index:color; arrows show directed edges.

Example 1:

Largest Color Value in a Directed Graph, example 1: illustration of the example

Input: colors = "bbab"
edges = [[0,1],[1,2],[2,3]]

Output: 3

Explanation: The path 0 → 1 → 2 → 3 has colors b, b, a, b. Color b appears 3 times, which is the largest color count possible in this graph.

Example 2:

Largest Color Value in a Directed Graph, example 2: illustration of the example

Input: colors = "abc"
edges = [[0,1],[2,2]]

Output: -1

Explanation: Node 2 has an edge back to itself, forming a directed cycle. The result is -1 even though the separate path 0 → 1 has no cycle.

Example 3:

Largest Color Value in a Directed Graph, example 3: illustration of the example

Input: colors = "abab"
edges = [[0,1],[0,2],[1,3],[2,3]]

Output: 2

Explanation: The path 0 → 1 → 3 contains two b-colored nodes. The path 0 → 2 → 3 contains two a-colored nodes. No directed path contains three occurrences of one color, so the maximum color value is 2.

Constraints:

  • n == colors.length
  • 1 <= n <= 100000
  • colors contains only lowercase English letters.
  • 0 <= edges.length <= 100000
  • Each edge contains two integer node labels between 0 and n - 1.
  • Self-loops and repeated directed edges are allowed.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.