Unweighted Graph Shortest Path Problem

You are tasked with finding the shortest path between two houses in the city of Ninjaland, represented as an unweighted graph. The city has N houses numbered from 1 to N and is connected by M bidirectional roads. Each road connects two houses, X and Y, allowing travel between them. It is guaranteed that every house is reachable from any other house.

Your goal is to determine the shortest path between two specified houses, S and T.

Example:

Input:
T = 1
N = 8, M = 8
S = 1, T = 8
Roads: [ (1, 2), (1, 3), (2, 5), (3, 4), (3, 8), (4, 6), (5, 8), (6, 7), (7, 8) ]
Output:
[1, 3, 8]
Explanation:

Multiple paths like (1, 2, 5, 8) or (1, 4, 6, 7, 8) exist but the shortest is (1, 3, 8).

Constraints:

  • 1 ≤ T ≤ 100
  • 2 ≤ N ≤ 103
  • 1 ≤ M ≤ min(N * (N - 1) / 2, 1000)
  • 1 ≤ S, T ≤ N
  • Time Limit: 1 sec
Note:
You do not need to print anything; the function implementation takes care of it. Return the shortest path as a sequence of house numbers.
AnswerBot
4mo

Find the shortest path between two houses in a city represented as an unweighted graph.

  • Use breadth-first search (BFS) algorithm to find the shortest path in an unweighted graph.

  • Start BFS from the sour...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Tower Research Capital LLC

Q. Design an application similar to MakeMyTrip.
Q. Check If Two Nodes Are Cousins You are given an arbitrary binary tree consisting...read more
Q. Counting Nodes in a Complete Binary Tree - Problem Statement Given the root of a...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