All problems
1178HardArrayStringTreeDepth-First SearchGraph TheoryTopological Sort

The Longest Run of Unlike Posts

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2246Longest Path With Different Adjacent Characters

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A tree has posts numbered 0 through n - 1, and post 0 sits at the top. above[i] names the post directly above post i, and above[0] is -1. Each post carries one lowercase letter, given by marks.

A run is a path through the tree that never repeats a post and along which no two neighbouring posts carry the same letter.

Return the largest number of posts a run can hold.

Examples

Example 1

Input
above = [-1, 0, 1, 2, 3], marks = "abcde"
Output
5

The posts form a single chain and no two neighbours share a letter, so the whole chain is one run.

Example 2

Input
above = [-1, 0], marks = "aa"
Output
1

Both posts carry the same letter, so no run can hold the two of them.

Example 3

Input
above = [-1, 0, 0, 0, 0, 0], marks = "abcdef"
Output
3

Five posts hang off the top one, all carrying different letters, so a run can come up one branch, through the top, and down another.

Constraints

  • 1 <= above.length <= 10^5
  • above.length == marks.length
  • above[0] == -1
  • above describes a tree with post 0 at the top
  • marks holds only lowercase English letters

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def longest_path(above: list[int], marks: str) -> int:
Java
public int longestPath(int[] above, String marks)
September 7
Apply