Shortest Distance Between Two Nodes
Updated
Problem statement
For this exercise, an undirected graph has n vertices labelled 0 through n-1. Each row [u,v] in edges joins u and v in both directions and has length one.
Return the minimum number of edges in any path from source to target. Return 0 if they are the same vertex, and -1 if no path connects them. Declared vertices with no incident edges still exist.
There are no self-loops or duplicate undirected edges. Cycles and disconnected components are allowed.
Function
shortestNodeDistance(n: int, edges: int[][], source: int, target: int) → intExamples
Example 1
n = 5edges = [[0,1],[1,2],[2,3],[0,4],[4,3]]source = 0target = 3return = 2The path 0 → 4 → 3 uses two edges, shorter than 0 → 1 → 2 → 3.
Example 2
n = 4edges = [[0,1]]source = 0target = 3return = -1Vertex 3 is isolated and cannot be reached from vertex 0.
Example 3
n = 1edges = []source = 0target = 0return = 0A vertex is zero edges away from itself, including an isolated vertex.
Constraints
- For this exercise, assume
1 <= n <= 500and0 <= edges.length <= 1000. - Each edge has exactly two valid, different indices in
[0,n-1]. Every undirected edge occurs once, in either orientation. sourceandtargetare valid indices. All supplied inputs satisfy these rules.
More Scale AI Onsite Interview questions
- Task Scheduler with DependenciesONSITE INTERVIEW · Seen Jul 2026
- Best Poker Category with a JokerPHONE SCREEN · ONSITE INTERVIEW · Seen Jun 2026
- Format and Validate a Model ResponseONSITE INTERVIEW · Seen Apr 2026
- Stateful Neuron Matrix UpdateONSITE INTERVIEW · Seen Apr 2026
- Clock Hand Angle with Subsecond PrecisionONSITE INTERVIEW · Seen Dec 2025
- Four-Player Matching Card GameONSITE INTERVIEW · Seen Feb 2025
- Rotate an Array to the RightONSITE INTERVIEW · Seen Oct 2024
- Rich-Text Segment Normalization and Bold ToggleONSITE INTERVIEW · Seen Apr 2024
- Minimum Distance Matching in a ForestPHONE SCREEN · ONSITE INTERVIEW · Seen Feb 2024
- Fit Beta Parameters by Maximum LikelihoodONSITE INTERVIEW · Seen Sep 2022
Similar questions at other companies
- Course ScheduleAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Course ScheduleOracle · ONSITE INTERVIEWOracle interview questions
- Course SchedulePlaud · ONSITE INTERVIEW
- Explore an Unknown Grid and Find a PathLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- Nearest Charging Station on a GridSpotify · ONSITE INTERVIEW
- Hierarchical Permission CheckeBay · ONSITE INTERVIEWeBay interview questions
- Shortest Path Node Count Avoiding Broken NodesGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Evaluate DivisionPhonePe · ONSITE INTERVIEWPhonePe interview questions
- Count Friend CirclesOpenAI · PHONE SCREEN · ONSITE INTERVIEWOpenAI interview questions
- Finite Web CrawlerMongoDB · PHONE SCREEN · ONSITE INTERVIEWMongoDB interview questions