Trains the technique from
LeetCode 2421Number of Good PathsThis 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 reserve has n shelter huts numbered 0 to n - 1. Hut i stands at height heights[i].
The huts are linked by n - 1 trails, handed over as an edge list trails, where trails[i] = [u, v] is a trail joining hut u and hut v. The trails link the whole reserve together and contain no loop, so between any two huts there is exactly one route that never visits a hut twice. That route is the trek between them.
A trek is level when both of the following hold:
Return how many level treks the reserve has. A single hut on its own counts as a level trek. A trek walked in one direction and the same trek walked back are one trek, counted once.
Example 1
Each of the three huts on its own is a level trek. The trek between hut 0 and hut 2 has matching ends at height 4, but it runs through hut 1, which stands at height 9, so it is not level.
Example 2
Every hut stands at height 2, so no route can pass a higher hut. The four single-hut treks and the six treks between different huts are all level.
Example 3
The five single-hut treks are level, and so are the trek from hut 0 to hut 1 and the trek from hut 3 to hut 4, both of which stay at height 1. Every other trek between two huts of height 1 runs through hut 2 at height 5.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def count_level_treks(heights: list[int], trails: list[list[int]]) -> int:public int countLevelTreks(int[] heights, int[][] trails)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.