VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-path-with-maximum-letter-frequency/

⇱ Longest Path with Maximum Letter Frequency - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Path with Maximum Letter Frequency

Last Updated : 23 Dec, 2023

Given a graph with n vertex and m-directed edges. One lowercase letter is assigned to each vertex. The value of the path is the number of the most frequently occurring letters in the path. The task is to find a path whose value is the largest.

Example:

Input: n = 5, m = 4, node_value = "abaca", edges[] = {1 2}, {1 3}, {3 4}, {4, 5}
Output: 3

Input: n = 6, m = 6, node_value = "xzyabc", edges[] = {1, 2}, {3, 1}, {2, 3}, {5, 4}, {4, 3}, {6, 4}
Output: -1

Approach:

The idea is to use dynamic programming to avoid redundant traversal of nodes. Use a 2-D array 'dp', where dp[i][j] represents the maximum count of character 'j' when reaching node i. 'i' ranges from 1 to N, and 'j' from 0 to 25 (representing 'a' to 'z'). Use topological sorting to calculate dp values, ensuring that nodes with edges to node 'i' are visited first. If a cycle is detected in the graph, the function returns -1 to indicate an infinitely large result due to repetitive traversal of the cycle.

Step-by-step approach:

  • Define 'inDegree' array for node indegrees, initially set to 0.
  • Iterate edges, updating 'inDegree' for each node.
  • Use a queue for topological order, enqueue nodes with 'inDegree' 0.
  • Pop the front element, increment character frequency in 'dp' array.
  • Update 'dp' array for adjacent nodes and adjust 'inDegree'.
  • Enqueue nodes with 'inDegree' 0 after updating.
  • If queue has elements after 'N' pops, return -1 (cycle detected).
  • Return the maximum element in the 'dp' array.

Below is the implementation of the above approach:


Output
Maximum path value: 3

Time Complexity: O(N), Where 'N' is the number of nodes in the given graph.
Auxiliary Space: O(N)

Comment