#1971

Find if Path Exists in Graph

Easy
Depth-First SearchBreadth-First SearchUnion-FindGraph TheoryGraph TraversalBreadth-First SearchDepth-First Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses BFS or DFS to traverse the graph efficiently, ensuring that we only explore each vertex once. This reduces unnecessary checks and improves performance significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build an adjacency list from the edges to represent the graph.
  2. 2Step 2: Initialize a queue (for BFS) or a stack (for DFS) and a visited set.
  3. 3Step 3: Start from the source, add it to the queue/stack, and explore all reachable vertices until the destination is found or all options are exhausted.
solution.py20 lines
1# Full working Python code
2from collections import defaultdict, deque
3
4def validPath(n, edges, source, destination):
5    graph = defaultdict(list)
6    for u, v in edges:
7        graph[u].append(v)
8        graph[v].append(u)
9
10    visited = set()
11    queue = deque([source])
12    while queue:
13        node = queue.popleft()
14        if node == destination:
15            return True
16        visited.add(node)
17        for neighbor in graph[node]:
18            if neighbor not in visited:
19                queue.append(neighbor)
20    return False

Complexity note: The time complexity is O(n) because we traverse each vertex and edge once. The space complexity is O(n) due to the storage of the graph in an adjacency list and the visited set.

  • 1Understanding graph traversal techniques is crucial.
  • 2Building an adjacency list is a common pattern in graph problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.