Problem · Array

Directed Path Existence

Learn this problem
EasyUnity logoUnityFULLTIMEOA

Problem statement

Parallel arrays fromNodes and toNodes encode directed edges fromNodes[i] → toNodes[i]. Return whether a directed path exists from start to target.

Duplicate edges and cycles are allowed. A node has a path to itself, even when it has no incident edge.

Function

pathExists(fromNodes: int[], toNodes: int[], start: int, target: int) → boolean

Examples

Example 1

fromNodes = [1,1,2,3]toNodes = [2,3,4,2]start = 1target = 4return = true

The path 1 → 2 → 4 reaches the target.

Example 2

fromNodes = [1,2,2,3]toNodes = [2,1,3,2]start = 3target = 4return = false

The cycle among nodes 1, 2, and 3 does not reach node 4.

Constraints

  • 0 <= fromNodes.length = toNodes.length <= 200000.
  • Every node label, including start and target, is an integer from 1 through 10^9.
  • Duplicate directed edges are ignored.
drafts saved locally
public boolean pathExists(int[] fromNodes, int[] toNodes, int start, int target) {
    // Write your code here.
}
fromNodes[1,1,2,3]
toNodes[2,3,4,2]
start1
target4
expectedtrue
checking account