Count Paths Whose Two Endpoints Both Hold the Path's Peak Score

Last updated: November 29, 2026

Quick Overview

In a tree of n nodes, each node has a score. Count the paths (including single nodes) whose two endpoints have equal scores and no node on the path has a larger score.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


In a tree of n nodes, each node has a score. Count the paths (including single nodes) whose two endpoints have equal scores and no node on the path has a larger score.

A demanding Google onsite question that rewards processing nodes in sorted order and merging components as they activate, a pattern also used in image segmentation. The interviewer checks that you see why every node on a valid path has a score at most the endpoints, and that you count pairs via per-component peak counts.

What the Interviewer Expects
  • Sorts nodes by score and activates them in that order
  • Only merges edges to already-activated neighbors
  • Keeps, per root, the max score and how many nodes hold it
  • Adds count_u * count_v when two components with the same peak merge
  • Includes single-node paths in the count
Key Topics to Cover
Union-Find
Sorting
Trees
Counting Pairs
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • What if the graph has cycles instead of being a tree?
  • Count paths where the endpoints hold the peak but need not be equal to each other.
  • How would you also return the longest such path?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: scores of length n and n - 1 undirected tree edges.
  • A good path has equal endpoint scores and no interior score above them.
  • Single nodes count. Paths are unordered.
  • Output: number o...
High-Level Design

Activate nodes in increasing score order. When activating v, union it only with neighbors whose score is at most scores[v]. Then every component contains only nodes with score at most the current ...


Submit Your Answer
Markdown supported