Count Nodes within K-Distance Problem Statement

Given a connected, undirected, and acyclic graph where some nodes are marked and a positive integer 'K'. Your task is to return the count of nodes such that the distance from each marked node is less than 'K'.

Explanation:

A connected graph means there is a path between every pair of vertices. Acyclic means the graph does not contain any cycles, and undirected means edges are bidirectional.

Input:

The first line contains two space-separated integers 'V' and 'E', representing the number of vertices and edges.
The next 'E' lines contain two space-separated integers denoting the vertices connected by an edge.
The following line contains an integer 'K'.
The subsequent line contains an integer 'M', the number of marked nodes.
Finally, the line contains 'M' space-separated integers denoting the marked nodes.

Output:

Output a single integer for each test case, representing the count of nodes with distances less than 'K' from all marked nodes.

Example:

Graph Example

Marked nodes are circled in red.
In the graph, nodes 1, 2, and 4 are marked. With K as 3, nodes 5, 9, 8, 2, 0, and 7 have distances less than 3 from all marked nodes. Hence, the total count is 6.

Constraints:

  • 1 <= 'V' <= 104
  • 0 <= 'E' <= 104
  • 1 <= |'V'| <= 'V'
  • 1 <= 'K' <= 35000
  • 1 <= 'M' <= 7000

Note:

No need to output, just implement the function as required.
AnswerBot
4mo

Count nodes within K-distance from marked nodes in a connected, undirected, acyclic graph.

  • Create an adjacency list to represent the graph.

  • Use BFS to traverse the graph and calculate distances from mar...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Comviva Technology

Q. Explain the concepts of OOP.
Q. Pillers of oops , explain data science, concepts of ACID
Q. Count Occurrences of X in Sorted Array Given a sorted array or list of integers ...read more
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits