πŸš€Day 18. Minimum Weight Cycle 🧠

The problem can be found at the following link: Question Link

πŸ’‘ Problem Description:

Given an undirected, weighted graph with V vertices numbered from 0 to V-1, and E edges, find the minimum weight cycle in the graph.

Each edge is represented by edges[i] = [u, v, w] meaning there is an edge between nodes u and v with weight w.

If no cycle exists, return -1.

⏰ Note: Sorry for uploading late, my Final Sem exam is going on.

πŸ” Example Walkthrough:

Example 1

Input:

V = 5
edges = [
    [0, 1, 2],
    [1, 2, 2],
    [1, 3, 1],
    [1, 4, 1],
    [0, 4, 3],
    [2, 3, 4]
]

Output:

Explanation:

Minimum-weighted cycle is 0 β†’ 1 β†’ 4 β†’ 0 with total weight = 2 + 1 + 3 = 6.

Example 2

Input:

Output:

Explanation:

Minimum-weighted cycle is 1 β†’ 3 β†’ 4 β†’ 1 with total weight = 1 + 2 + 2 = 5.

Constraints

  • $(1 \leq V \leq 100)$

  • $(1 \leq E = \text{edges.length} \leq 10^3)$

  • $(1 \leq \text{edges[i][j]} \leq 100)$

🎯 My Approach:

Dijkstra-Based (Per Node Check)

Algorithm Steps:

  1. Build an adjacency list from the edge list.

  2. For every node i from 0 to V-1:

    • Run Dijkstra's algorithm from node i to compute the shortest paths to all other nodes.

    • While processing neighbors, if you find a back-edge to an already visited node, and it doesn’t form a direct parent-child, it could form a cycle.

    • Update the minimum cycle weight if a better cycle is found.

  3. After checking from all nodes, return the minimum cycle length found, or -1 if no cycle exists.

βœ… Why It Works

  • Each shortest path computed from i guarantees minimal distance to v, so combining two shortest paths and an extra edge efficiently checks all minimal cycles passing through that edge.

  • The parent check ensures we’re not just tracing the same edge forward and backward.

πŸ•’ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(V Γ— E Γ— log V), since we run Dijkstra's algorithm (O(E log V)) for each vertex.

  • Expected Auxiliary Space Complexity: O(V + E), to store the adjacency list, distance array, parent tracking, and priority queue per run.

πŸ“ Solution Code

Code (C++)

Code (Java)

Code (Python)

🎯 Contribution and Support:

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Last updated