Doctor Ninja's House Problem Statement

In a network of 'N' cities with 'M' paths connecting them, Doctor Ninja aims to purchase a house in a city 'X' such that it is possible to reach every other city from city 'X'. Your task is to determine the city 'X'.

If there are multiple options for city 'X', select the city with the smallest number. If no such city exists, return -1.

Example:

Input:
T = 1
N = 8, M = 10
Paths:
0 1
0 2
1 3
2 3
2 4
3 5
4 5
4 6
5 7
6 7
Output:
0
Explanation:

In the given graph configuration, city 0 can reach all the other cities either directly or indirectly, making it the mother vertex. Thus, the output is 0.

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 104
  • 1 <= M <= 105
  • 0 <= X < N
  • Time Limit: 1 sec.
Note:

You are not responsible for printing anything, as this is handled externally. Your task is to implement the function to find the solution.

AnswerBot
1y

The task is to find a city 'X' from which all other cities can be reached in a given graph.

  • Find the mother vertices in the graph.

  • If there are multiple mother vertices, return the minimum value.

  • If ther...read more

Help your peers!
Select
Add answer anonymously...
Wunderman Thompson Commerce Technical Associate 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