FastPrepDistances While Avoiding a Broken Node

Distances While Avoiding a Broken Node

Google logoGoogle● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

You are given a directed unweighted graph with vertices 0 through n-1, a start vertex, and one broken vertex that cannot be visited.

Return the minimum edge distance from start to every vertex while never visiting the broken vertex. Use -1 for unreachable vertices, including the broken vertex. If start is broken, return all -1.

Cycles and duplicate edges are allowed.

Function

distancesAvoidingBroken(n: int, edges: int[][], start: int, broken: int) → int[]

Examples

Example 1

n = 5edges = [[0,1],[1,2],[0,3],[3,2],[2,4]]start = 0broken = 1return = [0,-1,2,1,3]

Vertex 2 is reached through 0→3→2 because vertex 1 is unavailable.

Example 2

n = 3edges = [[0,1],[1,2],[2,0]]start = 0broken = 2return = [0,1,-1]

The cycle is handled without revisiting vertices.

Example 3

n = 3edges = [[0,1]]start = 1broken = 1return = [-1,-1,-1]

A broken start cannot reach any vertex.

Constraints

  • 1 <= n <= 200000.
  • 0 <= edges.length <= 400000.
  • Every edge contains two valid vertex IDs.
  • start and broken are valid vertices.

More Google problems

See Google hiring insights
public int[] distancesAvoidingBroken(int n, int[][] edges, int start, int broken) {
    // Write your code here.
}
n5
edges[[0,1],[1,2],[0,3],[3,2],[2,4]]
start0
broken1
expected[0,-1,2,1,3]
Checking account…