698. Most Common Colour on a Path

A pipeline of n tasks is numbered 0 to n - 1. The string colours gives each task a lowercase letter label, so task i has the label colours[i]. Each pair [a, b] in edges is a one-way link from task a to task b; duplicate links and self-links may occur.

A path follows links one after another and may consist of a single task. The dominance of a path is how many times its most frequent label appears on it. Return the largest dominance over all paths. If the links contain a cycle, paths can be arbitrarily long, so return -1 instead. Aim for O(26 * (n + m)) time with m = edges.length.

Example 1

Input:
colours = "bccbcd"edges = [[0,1],[1,2],[2,3],[3,4],[4,5]]
Output:
3
Explanation:

The only path runs through all six tasks and contains the label c three times, more than any other label.

Example 2

Input:
colours = "ab", edges = [[0,1],[1,0]]
Output:
-1
Explanation:

Tasks 0 and 1 link to each other, which is a cycle, so the answer is -1.

Example 3

Input:
colours = "rggbg"edges = [[0,1],[0,2],[1,3],[2,3],[3,4]]
Output:
2
Explanation:

Both paths from task 0 to task 4 pass through the labels r, g, b, g; the label g appears twice, which is the best possible.

Constraints

1 ≤ n = colours.length ≤ 30000

0 ≤ edges.length ≤ 30000

0 ≤ a, b < n for every link [a, b]

colours consists of lowercase English letters.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms

Expected complexity

Time
O(26 * (n + m))
Space
O(n + m)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…