Skip to main content
All Questions

Count the valid paths passing through each node of a tree.

Unlock detailed company stats for this questionUpgrade

You are given an undirected tree with N nodes numbered 1 to N. A path is a sequence of one or more edges connecting two distinct nodes; (u, v) and (v, u) are the same path, and single-node paths are not valid. For every node i, determine the number of distinct valid paths that contain node i, modulo 10^9 + 7. Example: tree 1-2-3 has valid paths (1,2), (2,3), (1,2,3), so the output is 2 3 2. Input: T test cases; each has N, then N-1 lines of edges u v. Output: N integers per test case, the i-th being the count for node i. Sample input: 2 / 3 / 1 2 / 2 3 / 2 / 1 2. Sample output: 2 3 2 and 1 1. Constraints: 1 <= T <= 10, 2 <= N <= 210^5, sum of N across tests <= 210^5.

Format · Online assessment.

Community answers

No answers contributed by the community yet.

Related courses

Course

Software Engineering Interview Prep

Land your dream software engineering role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates—practice data structures, algorithms, system design, people management, behavioral interviews, and more.

Course

System Design Interviews

Learn how to answer the latest system design questions across product, infrastructure, and AI domains. Features in-depth video examples, written breakdowns, and helpful reference patterns. Watch senior engineers and managers answer these questions in mock interview videos.