Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Shortest Cycle in a Graph

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2608" 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

There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1. The edges in the graph are represented by a given 2D integer array edges, where edges[i] = [ui, vi] denotes an edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. Return the length of the shortest cycle in the graph. If no cycle exists, return -1. A cycle is a path that starts and ends at the same node, and each edge in the path is used only once. Example 1: Input: n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]] Output: 3 Explanation: The cycle with the smallest length is : 0 -> 1 -> 2 -> 0 Example 2: Input: n = 4, edges = [[0,1],[0,2]] Output: -1 Explanation: There are no cycles in this graph. Constraints: 2 <= n <= 1000 1 <= edges.length <= 1000 edges[i].length == 2 0 <= ui, vi < n ui != vi There are no repeated edges.

Explanation

Here's an efficient approach to find the shortest cycle in a bi-directional graph:

  • Breadth-First Search (BFS): Perform BFS from each node in the graph. The goal is to find the shortest path back to the starting node.

  • Cycle Detection: During BFS, maintain the parent of each node in the path. If we encounter a neighbor that is already visited and is not the parent of the current node, we've found a cycle. The length of this cycle is the distance from the starting node to the current node + 1 + distance from start node to visited neighbor.

  • Minimum Cycle Length: Keep track of the minimum cycle length found so far and update it whenever a shorter cycle is detected.

  • Time & Space Complexity: O(n * (n + m)), where n is the number of vertices and m is the number of edges. The space complexity is O(n + m).

Code

    from collections import deque

def shortest_cycle(n, edges):
    """
    Finds the length of the shortest cycle in a bi-directional graph.

    Args:
        n: The number of vertices in the graph.
        edges: A list of edges, where each edge is a list [u, v].

    Returns:
        The length of the shortest cycle in the graph, or -1 if no cycle exists.
    """

    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
        adj[v].append(u)

    min_cycle_len = float('inf')

    for start_node in range(n):
        q = deque([(start_node, -1, 0)])  # (node, parent, distance)
        visited = {start_node}

        while q:
            node, parent, distance = q.popleft()

            for neighbor in adj[node]:
                if neighbor == parent:
                    continue

                if neighbor in visited:
                    cycle_len = distance + 1 + 1  # Distance back to start node, + 1 for node->neighbor + distance to the start node (1 in our case because neighbor to startnode)
                    min_cycle_len = min(min_cycle_len, cycle_len)
                else:
                    visited.add(neighbor)
                    q.append((neighbor, node, distance + 1))


    if min_cycle_len == float('inf'):
        return -1
    else:
        return min_cycle_len

More from this blog

C

Chatmagic blog

2894 posts