VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-nodes-at-a-distance-k-for-every-node/

⇱ Count of nodes at a distance K for every node - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of nodes at a distance K for every node

Last Updated : 23 Jul, 2025

Given a tree of N vertices and a positive integer K. The task is to find the count of nodes at a distance K for every node.

Examples:

Input: N = 5, K = 2, edges[][] = {{1, 2}, {1, 3}, {2, 4}, {2, 5}}
Output: 2 1 1 2 2
Explanation:

  • From node 1, there are 2 nodes that are at a distance of 2: node 4 and node 5.
  • From node 2, there is 1 node that is at a distance of 2: node 3.
  • From node 3, there is 1 node that is at a distance of 2: node 2.
  • From node 4, there are 2 nodes that are at a distance of 2: node 1 and node 5.
  • From node 5, there are 2 nodes that are at a distance of 2: node 1 and node 4.

Input: N = 5 K = 3, edges[][] = {{1, 2}, {2, 3}, {3, 4}, {4, 5}}
Output: 1 1 0 1 1

Approach: To solve the problem, follow the below idea:

The approach involves a depth-first search (DFS) traversal of the tree starting from each node to efficiently count the number of nodes at a distance K from all nodes.

Step-by-step algorithm:

  • Perform a DFS traversal from a given node v. It keeps track of the current distance d from the starting node and the target distance K to find nodes at distance k from the starting node.
  • During the traversal, it marks each visited node and updates the distance of each node from the starting node.
  • If the current distance d equals the target distance k, it increments the count of nodes at distance k (ans[v]++).
  • If the current distance d exceeds the target distance k, it returns without further exploration, as nodes beyond distance k are not considered.
  • For each adjacent node u of the current node v, if u has not been visited yet, the dfs function is called recursively to explore u with an incremented distance d+1.
  • After performing the DFS traversal from each node, output the count of nodes at distance k for each node in the tree.

Below is the implementation of the above approach:


Output
1 2
2 1
3 1
4 2
5 2

Time complexity: O(N * K), where N is the number of nodes and K is the distance between the nodes.
Auxiliary Space: O(N * K)

Comment
Article Tags:
Article Tags: