LeetCode solutions

2121. Find if Path Exists in Graph

My accepted Python solution to LeetCode problem 2121, Find if Path Exists in Graph, running in 311ms.

  • Difficulty: Easy
  • Python
  • Runtime 311ms
  • Memory 94.6MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 311ms, memory 94.6MB, accepted 2025-12-31.

python
class Solution:
    def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
        if source == destination:
            return True
        graph = defaultdict(list)
        for u, v in edges:
            graph[u].append(v)
            graph[v].append(u)
        visited = set([source])
        queue = deque([source])
        while queue:
            node = queue.popleft()
            if node == destination:
                return True
            for neighbor in graph[node]:
                if neighbor not in visited:
                    visited.add(neighbor)
                    queue.append(neighbor)
        return False

Source