Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Find Closest Node to Given Two Nodes

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2359" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

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]. If there is no outgoing edge from i, then edges[i] == -1. You are also given two integers node1 and node2. Return the index of the node that can be reached from both node1 and node2, such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1. Note that edges may contain cycles. Example 1: 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. Example 2: Input: edges = [1,2,-1], node1 = 0, node2 = 2 Output: 2 Explanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0. The maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2. Constraints: n == edges.length 2 <= n <= 105 -1 <= edges[i] < n edges[i] != i 0 <= node1, node2 < n

Explanation

Here's the breakdown of the solution:

  • Compute Distances: Calculate the distances from node1 and node2 to all other reachable nodes in the graph. We use arrays to store these distances, initializing them with infinity to represent unreachable nodes.
  • Find Common Reachable Nodes: Iterate through all nodes to find nodes that are reachable from both node1 and node2 (i.e., have finite distances in both distance arrays).
  • Minimize Maximum Distance: Among the common reachable nodes, find the node that minimizes the maximum of the two distances. If multiple such nodes exist, return the node with the smallest index.

  • Runtime Complexity: O(N), where N is the number of nodes. Storage Complexity: O(N)

Code

    def closestMeetingNode(edges, node1, node2):
    n = len(edges)
    dist1 = [float('inf')] * n
    dist2 = [float('inf')] * n

    def bfs(start_node, dist):
        dist[start_node] = 0
        curr = start_node
        while curr != -1:
            neighbor = edges[curr]
            if neighbor != -1 and dist[neighbor] == float('inf'):
                dist[neighbor] = dist[curr] + 1
                curr = neighbor
            else:
                break

    bfs(node1, dist1)
    bfs(node2, dist2)

    min_max_dist = float('inf')
    result = -1

    for i in range(n):
        if dist1[i] != float('inf') and dist2[i] != float('inf'):
            max_dist = max(dist1[i], dist2[i])
            if max_dist < min_max_dist:
                min_max_dist = max_dist
                result = i
            elif max_dist == min_max_dist and i < result:
                result = i

    return result

More from this blog

C

Chatmagic blog

2894 posts