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

Leetcode #2359: Find Closest Node to Given Two Nodes

In this guide, we solve Leetcode #2359 Find Closest Node to Given Two Nodes 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

You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i].

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Depth-First Search, 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: edges = [2,2,3,-1], node1 = 0, node2 = 1 Output: 2 Explanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1. The maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2.

Python Solution

class Solution: def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: def f(i): dist = [inf] * n dist[i] = 0 q = deque([i]) while q: i = q.popleft() for j in g[i]: if dist[j] == inf: dist[j] = dist[i] + 1 q.append(j) return dist g = defaultdict(list) for i, j in enumerate(edges): if j != -1: g[i].append(j) n = len(edges) d1 = f(node1) d2 = f(node2) ans, d = -1, inf for i, (a, b) in enumerate(zip(d1, d2)): if (t := max(a, b)) < d: d = t ans = i return ans

Complexity

The time complexity is O(V+E). The space complexity is O(n)O(n)O(n), where nnn is the number of nodes.

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