FastPrepMutual Station Connectivity Queries

Mutual Station Connectivity Queries

Bloomberg LP logoBloomberg LP● HardNEW GRADPHONE SCREEN
Learn

Problem statement

A directed subway network has stations labeled from 0 through n - 1. Each row [from, to] in connections means trains can travel directly from from to to.

For each row [a, b] in queries, determine whether a can reach b and b can reach a through zero or more directed connections. A station is mutually reachable with itself.

Return the query answers in order.

Function

mutuallyConnected(n: int, connections: int[][], queries: int[][]) → boolean[]

Examples

Example 1

n = 5connections = [[0,1],[1,2],[2,0],[2,3],[3,4],[4,3]]queries = [[0,2],[0,3],[3,4],[4,0],[1,1]]return = [true,false,true,false,true]

Stations 0, 1, 2 form one strongly connected component, while 3, 4 form another. The edge from 2 toward 3 does not provide a path back.

Example 2

n = 4connections = [[0,1],[1,0],[2,3]]queries = [[0,1],[0,2],[2,3],[3,3]]return = [true,false,false,true]

Only stations 0 and 1 are distinct mutually reachable stations. The one-way edge 2 → 3 is insufficient, and a station always reaches itself.

Example 3

n = 1connections = []queries = [[0,0]]return = [true]

The only station is mutually reachable with itself through a zero-edge path.

Constraints

  • 1 <= n <= 100000.
  • 0 <= connections.length <= 200000.
  • 1 <= queries.length <= 100000.
  • Every station index in connections and queries is between 0 and n - 1.
  • Connections may contain self-loops or duplicate edges.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public boolean[] mutuallyConnected(int n, int[][] connections, int[][] queries) {
    // Write your code here.
}
n5
connections[[0,1],[1,2],[2,0],[2,3],[3,4],[4,3]]
queries[[0,2],[0,3],[3,4],[4,0],[1,1]]
expected[true,false,true,false,true]
Checking account…