Problem

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 English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj.

A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.

Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.

Examples

Example 1:

graph LR;
A(0):::red --> C(2):::red --> D(3):::blue --> E(4):::red
A --> B(1):::purple


classDef red fill:#FF0000,stroke:#000,stroke-width:1px,color:#fff;
classDef blue fill:#ADD8E6,stroke:#000,stroke-width:1px;
classDef purple fill:#DDA0DD,stroke:#333,stroke-width:2px;
  
1
2
3
Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
Output: 3
Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image).

Example 2:

graph LR;
A(0):::red --> A

classDef red fill:#FF0000,stroke:#000,stroke-width:1px,color:#fff;
  
1
2
3
Input: colors = "a", edges = [[0,0]]
Output: -1
Explanation: There is a cycle from 0 to 0.

Constraints:

  • n == colors.length
  • m == edges.length
  • 1 <= n <= 105
  • 0 <= m <= 105
  • colors consists of lowercase English letters.
  • 0 <= aj, bj < n

Solution

Method 1 - Using Topological Sort

We need to compute the maximum colour count along paths in a directed graph while detecting cycles (in which case the problem becomes invalid). Topological Sorting is ideal for processing nodes in a directed acyclic graph. While traversing, maintain colour frequencies at each node from incoming neighbours.

Approach

  1. Build the Graph:
    • Construct adjacency list from the edges.
    • Count incoming edges (in-degree) for each node to determine the starting points for topological sorting.
  2. Topological Sort:
    • Use a queue to perform BFS-based topological sort, starting with nodes having 0 in-degree.
    • Maintain the count of visited nodes to detect cycles.
  3. Track Colour Counts:
    • During BFS, propagate colour frequency counts to successor nodes.
    • Update the counts if higher frequencies are found.
  4. Cycle Detection:
    • If the number of processed nodes is fewer than n, a cycle is present (return -1).
  5. Output Maximum Value:
    • Return the maximum colour count among all paths.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class Solution {
    public int largestPathValue(String colors, int[][] edges) {
        int n = colors.length();
        int[] inDegree = new int[n];
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
        
        for (int[] edge : edges) {
            graph.get(edge[0]).add(edge[1]);
            inDegree[edge[1]]++;
        }
        
        Queue<Integer> q = new LinkedList<>();
        int[][] colorCount = new int[n][26];  // Frequency of colors per node
        for (int i = 0; i < n; i++) {
            if (inDegree[i] == 0) q.add(i);
        }
        
        int visited = 0, ans = 0;
        
        while (!q.isEmpty()) {
            int node = q.poll();
            visited++;
            colorCount[node][colors.charAt(node) - 'a']++; // Increase own color count
            
            ans = Math.max(ans, Arrays.stream(colorCount[node]).max().getAsInt());
            
            for (int next : graph.get(node)) {
                for (int i = 0; i < 26; i++) {
                    colorCount[next][i] = Math.max(colorCount[next][i], colorCount[node][i]);
                }
                if (--inDegree[next] == 0) q.add(next);
            }
        }
        
        return visited == n ? ans : -1; // Check for cycles
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
    def largestPathValue(self, colors: str, edges: List[List[int]]) -> int:
        n = len(colors)
        in_deg = [0] * n
        graph = defaultdict(list)
        
        for u, v in edges:
            graph[u].append(v)
            in_deg[v] += 1
        
        q = deque([i for i in range(n) if in_deg[i] == 0])
        color_count = [[0] * 26 for _ in range(n)]  # Frequency of colors per node
        
        visited = 0
        ans = 0
        
        while q:
            node = q.popleft()
            visited += 1
            color_count[node][ord(colors[node]) - ord('a')] += 1  # Increase own color count
            
            ans = max(ans, max(color_count[node]))
            
            for next_node in graph[node]:
                for i in range(26):
                    color_count[next_node][i] = max(color_count[next_node][i], color_count[node][i])
                in_deg[next_node] -= 1
                if in_deg[next_node] == 0:
                    q.append(next_node)
        
        return ans if visited == n else -1  # Check for cycles

Complexity

  • ⏰ Time complexity: O(n + m * c)
    • n: Number of nodes, m: Number of edges, c: Number of distinct colours (bounded by 26 since colours are lowercase English letters).
    • Graph traversal and updating counts at each edge dominate.
  • 🧺 Space complexity: O(n * c + m)
    • Colour count array per node (n * c), adjacency list (m).