FastPrepPath Existence in an Undirected Graph
Problem · Graph

Path Existence in an Undirected Graph

Learn this problem
EasyByteDance logoByteDanceFULLTIMEPHONE SCREEN

Problem statement

You are given an undirected graph with n vertices numbered from 0 to n - 1. The array edges contains one unordered pair [u, v] for each edge between vertices u and v.

Return true if a path connects source to destination. Otherwise, return false.

A vertex always has a path to itself, including an isolated vertex.

Function

validPath(n: int, edges: int[][], source: int, destination: int) → boolean

Examples

Example 1

n = 3edges = [[0,1],[1,2],[2,0]]source = 0destination = 2return = true

The edge between 0 and 2 directly connects the two vertices.

Example 2

n = 6edges = [[0,1],[0,2],[3,5],[5,4],[4,3]]source = 0destination = 5return = false

Vertices 0 and 5 belong to different connected components.

Example 3

n = 1edges = []source = 0destination = 0return = true

The source and destination are the same isolated vertex.

Constraints

  • 1 <= n <= 200000.
  • 0 <= edges.length <= 200000.
  • Every edge contains two valid vertex numbers.
  • 0 <= source, destination < n.
  • The graph may contain cycles, disconnected components, and repeated edges.

More ByteDance problems

drafts saved locally
public boolean validPath(int n, int[][] edges, int source, int destination) {
    // Write your solution here.
}
n3
edges[[0,1],[1,2],[2,0]]
source0
destination2
expectedtrue
checking account