Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1971: Find if Path Exists in Graph

In this guide, we solve Leetcode #1971 Find if Path Exists in Graph in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi.

Quick Facts

  • Difficulty: Easy
  • Premium: No
  • Tags: Depth-First Search, Breadth-First Search, Union Find, Graph

Intuition

The data forms a graph, so we should explore nodes and edges systematically.

A traversal ensures we visit each node once while maintaining the needed state.

Approach

Build an adjacency list and traverse with BFS or DFS.

Aggregate results as you visit nodes.

Steps:

  • Build the graph.
  • Traverse with BFS/DFS.
  • Accumulate the required output.

Example

Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2 Output: true Explanation: There are two paths from vertex 0 to vertex 2: - 0 → 1 → 2 - 0 → 2

Python Solution

class Solution: def validPath( self, n: int, edges: List[List[int]], source: int, destination: int ) -> bool: def dfs(i: int) -> bool: if i == destination: return True vis.add(i) for j in g[i]: if j not in vis and dfs(j): return True return False g = [[] for _ in range(n)] for u, v in edges: g[u].append(v) g[v].append(u) vis = set() return dfs(source)

Complexity

The time complexity is O(n+m)O(n + m)O(n+m), and the space complexity is O(n+m)O(n + m)O(n+m). The space complexity is O(n+m)O(n + m)O(n+m).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy