Problem · Graph

Distance to the Nearest Supply Point

Learn this problem
MediumLinkedIn logoLinkedInFULLTIMEONSITE INTERVIEW

Problem statement

There are n locations numbered from 0 through n - 1. The undirected array roads contains the available connections, where roads[i] = [u, v] joins two locations and traversing one road has distance 1.

Some locations in supplyPoints contain supplies. Given a landingPoint, return the minimum number of roads needed to reach any supply point. Return -1 if no supply point is reachable.

Function

nearestSupplyDistance(n: int, roads: int[][], supplyPoints: int[], landingPoint: int) → int

Examples

Example 1

n = 6roads = [[0,1],[1,2],[2,3],[1,4],[4,5]]supplyPoints = [3,5]landingPoint = 0return = 3

Both supply locations are three roads from location 0, so the nearest distance is 3.

Example 2

n = 5roads = [[0,1],[1,2],[3,4]]supplyPoints = [4]landingPoint = 0return = -1

The landing point and the only supply point are in different connected components.

Constraints

  • 1 <= n <= 200000.
  • 0 <= roads.length <= 200000.
  • Every road endpoint, supply point, and the landing point is a valid location.
  • Supply points are unique.
  • Parallel roads do not change the answer.

More LinkedIn problems

drafts saved locally
public int nearestSupplyDistance(int n, int[][] roads, int[] supplyPoints, int landingPoint) {
    // Write your code here.
}
n6
roads[[0,1],[1,2],[2,3],[1,4],[4,5]]
supplyPoints[3,5]
landingPoint0
expected3
checking account