




Sponsored
Sponsored
This approach leverages a topological sort using Kahn's algorithm to process nodes in an order that respects the directed edges. We use an additional data structure to keep a running tally of the frequency of each color at every node, and update these tallies as we process nodes. This allows us to track the most frequently occurring color for all paths.
If we detect any cycles during this process, we can immediately return -1.
Time Complexity: O(n + m), where n is the number of nodes and m is the number of edges. This accounts for the initial processing of nodes and edges and the BFS traversal of the graph.
Space Complexity: O(n), mainly due to the adjacency list, in-degree array, and color count table.
1from collections import defaultdict, deque
2
3def largest_path_value(colors, edges):
4    # Convert edge list to an adjacency list
5    n = len(colors)
6    adj_list = defaultdict(list)
7    in_degree = [0] * n
8    
9    for u, v in edges:
10        adj_list[u].append(v)
11        in_degree[v] += 1
12        
13    # Queue for nodes with zero in-degree
14    queue = deque()
15    color_count = [[0] * 26 for _ in range(n)]
16    
17    # Initialize the queue with all nodes with in-degree zero
18    for i in range(n):
19        if in_degree[i] == 0:
20            queue.append(i)
21            color_count[i][ord(colors[i]) - ord('a')] = 1
22    
23    node_count = 0
24    max_color_value = 0
25    
26    while queue:
27        node = queue.popleft()
28        node_count += 1
29        max_color_value = max(max_color_value, max(color_count[node]))
30        
31        for neighbor in adj_list[node]:
32            for color in range(26):
33                color_count[neighbor][color] = max(color_count[neighbor][color], color_count[node][color] + (1 if color == ord(colors[neighbor]) - ord('a') else 0))
34            in_degree[neighbor] -= 1
35            if in_degree[neighbor] == 0:
36                queue.append(neighbor)
37    
38    return max_color_value if node_count == n else -1The implementation starts by constructing an adjacency list from the edges and calculates the in-degree for each node. We use Kahn's algorithm to perform a topological sort, starting with nodes with zero in-degree.
During the processing, we maintain a color frequency table for each node, updating the table as we process each node's neighbors. If the node count at the end doesn't match the number of nodes, a cycle exists, and we return -1. Otherwise, we return the maximum color frequency value found.
This approach applies a Depth-First Search (DFS) on each node while using memoization to store and retrieve previously computed results. This aids in finding the most frequent color along paths derived from each node.
During DFS, we also check for cycles by marking nodes as currently being visited, immediately returning -1 upon detecting a cycle.
Time Complexity: O(n + m), for processing nodes, edges, and DFS traversal.
Space Complexity: O(n), driven by memoization and state tracking.
1#include <vector>
2#include <string>
3#include <algorithm>
4#include <unordered_map>
5
using namespace std;
class Solution {
public:
    int largestPathValue(string colors, vector<vector<int>>& edges) {
        int n = colors.size();
        vector<vector<int>> adjList(n);
        vector<vector<int>> memo(n, vector<int>(26, 0));
        vector<int> state(n, 0);
        
        for (auto& edge : edges) {
            adjList[edge[0]].push_back(edge[1]);
        }
        int maxColorValue = -1;
        for (int node = 0; node < n; ++node) {
            int value = dfs(node, colors, adjList, state, memo);
            if (value == -1) return -1;
            maxColorValue = max(maxColorValue, value);
        }
        return maxColorValue;
    }
private:
    int dfs(int node, const string& colors, vector<vector<int>>& adjList, 
            vector<int>& state, vector<vector<int>>& memo) {
        if (state[node] == 1) return -1; // cycle detected
        if (state[node] == 2) return *max_element(memo[node].begin(), memo[node].end());
        
        state[node] = 1; // mark as visiting
        for (int neighbor : adjList[node]) {
            int result = dfs(neighbor, colors, adjList, state, memo);
            if (result == -1) return -1;
            for (int i = 0; i < 26; ++i) {
                memo[node][i] = max(memo[node][i], memo[neighbor][i]);
            }
        }
        
        // add this node's color
        memo[node][colors[node] - 'a']++;
        state[node] = 2; // mark as visited
        return *max_element(memo[node].begin(), memo[node].end());
    }
};The C++ solution utilizes DFS to explore paths from all nodes. During exploration, if a node is detected as currently being visited, it indicates a cycle, and we return -1.
A memoization table stores the frequency of colors for paths from each node. After processing all nodes, the highest frequency from the table is the desired result.