Distances to the Nearest Infected Node
Updated
Problem statement
You are given an undirected, unweighted graph with n nodes numbered from 0 to n - 1. The array infected contains the distinct nodes that are already infected.
Return an integer array distance of length n, where distance[v] is the minimum number of edges on a path from node v to any infected node. Return -1 for a node that cannot reach any infected node.
Function
nearestInfectedDistances(n: int, edges: int[][], infected: int[]) → int[]Examples
Example 1
n = 7edges = [[0,1],[1,2],[2,3],[4,5]]infected = [0,3,5]return = [0,1,1,0,1,0,-1]Nodes 0, 3, and 5 start at distance 0. Nodes 1, 2, and 4 are one edge from an infected node. Node 6 is isolated, so its distance is -1.
Example 2
n = 5edges = [[0,1],[1,2],[2,3],[3,4]]infected = [1,4]return = [1,0,1,1,0]A shortest path may end at either infected source. Node 3, for example, is one edge from node 4.
Constraints
1 <= n <= 2000000 <= edges.length <= 200000- Every row of
edgesis[u, v]with0 <= u, v < nandu != v. 1 <= infected.length <= n- All entries of
infectedare distinct valid node indices.
More Google Onsite Interview questions
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Cheapest Flights Within K StopsAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Fire Station Response BillLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- Minimum Friend API CallsMercor · ONSITE INTERVIEWMercor interview questions
- Shortest Increasing Path to a TargetUber · ONSITE INTERVIEWUber interview questions
- Find and Reconstruct a Binary-Matrix PathMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Open the Lock and Return a Shortest PathZip · PHONE SCREEN · ONSITE INTERVIEWZip interview questions
- Shortest Travel Time in a Grid with Traffic LightsWaymo · PHONE SCREENWaymo interview questions
- Delivery Management SystemAkuna Capital · OAAkuna Capital interview questions
- Shortest Word Chain Between Two WordsFanatics · PHONE SCREEN
- Shortest Path from an Encoded GraphIntuit · OAIntuit interview questions