Python coding

Most repeated label on a path

A directed graph has n = len(labels) nodes numbered 0 to n - 1. Node i carries the lowercase letter labels[i], and each pair [a, b] in edges is an edge from a to b. A path is any sequence of nodes where each step follows an edge; a single node counts. Its score is how many times its most frequent letter appears on it. Return the highest score of any path, or -1 if the graph has a cycle anywhere (a path could then loop forever).

labels is not empty; edges may repeat, and a self-loop is a cycle.

Besides the tests, one large input (40 nodes, over 4 million paths) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • most_repeated_label("abaca", [[0,1],[0,2],[2,3],[3,4]]) → 3
  • most_repeated_label("ab", [[0,1],[1,0]]) → -1
  • most_repeated_label("xyz", []) → 1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

The number of paths can grow exponentially, so don't walk them. For each letter, the best path ending at v extends the best path ending at one of v's predecessors: DP in topological order.

Hint 2

Process nodes in Kahn's order, keeping 26 counts per node: the most of each letter on any path ending there. Pass them along each edge with an element-wise max.

Hint 3

Add one for the node's own letter only when you pop it, once all its predecessors are in. If fewer than n nodes come out, there is a cycle: return -1.

Solution and why it works
pythonO(26·(n + E)), E = len(edges) · O(26·n + E)
from collections import deque


def most_repeated_label(labels: str, edges: list[list[int]]) -> int:
    n = len(labels)
    out, indeg = [[] for _ in range(n)], [0] * n
    for a, b in edges:
        out[a].append(b)
        indeg[b] += 1
    most = [[0] * 26 for _ in range(n)]     # most[v][c]: most c's on a path ending at v
    queue = deque(v for v in range(n) if indeg[v] == 0)
    done = best = 0
    while queue:
        v = queue.popleft()
        done += 1
        c = ord(labels[v]) - 97
        most[v][c] += 1                     # every path into v is already folded in
        best = max(best, most[v][c])
        for w in out[v]:
            most[w] = [max(x, y) for x, y in zip(most[w], most[v])]   # max, never sum
            indeg[w] -= 1
            if indeg[w] == 0:
                queue.append(w)
    return best if done == n else -1        # nodes left over sit on or behind a cycle

It is a longest-path DP on a DAG, one per letter, run in topological order. Kahn's algorithm pops a node only after all its predecessors, so its 26 counts are final then: add its own letter and push the counts forward. Traps: summing counts from two predecessors (a diamond of four as scores 3, but summing gives 5); tracking only the single best letter, since another can win later; and enumerating paths, which is exponential. A short Kahn order means a cycle.