Ctrl K

Routes Between Equal Peaks

Hard
Mountain camps are numbered 0 to n - 1 and joined by trails that form a tree: any two camps are connected by exactly one path with no repeats. heights[i] is the height of camp i, and links[j] = [a, b] is a trail between camps a and b. A **route** is a simple path along the trails such that: - its first and last camps are at the same height; - no camp on the path is higher than its ends. A single camp on its own is also a route. A path and its reverse count as the same route. Return the number of distinct routes.
Example 1
heights=[2, 1, 2, 3], links=[[0, 1], [1, 2], [2, 3]] → 5

Four single-camp routes plus one more: 0 → 1 → 2. Its ends are at height 2 and camp 1 is lower. No route can end at camp 3: it is higher and alone at its height.

Example 2
heights=[1, 4, 1], links=[[0, 1], [1, 2]] → 3

Camps 0 and 2 share a height, but the path between them crosses the higher camp 1. Only the three single-camp routes remain.

Example 3
heights=[5, 5, 1], links=[[0, 2], [1, 2]] → 4
Constraints
  • n == len(heights)
  • 1 ≤ n ≤ 3·10⁴
  • 0 ≤ heights[i] ≤ 10⁵
  • len(links) == n - 1
  • 0 ≤ a, b < n, a ≠ b
  • The trails form a tree
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRooms Open from the Hall MediumWhich Machine to Cure HardWhich Machine to Unplug HardCell Levels by Rows and Columns HardScooter Trips Under a Road Limit Hard
loading Python…
Input
heights=[2, 1, 2, 3], links=[[0, 1], [1, 2], [2, 3]]
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 83 tests on the server, hidden ones included.