714334. Min Time

Hard

Min Time

Summary

The Min Time problem involves finding the minimum time it takes to visit a set of cities, given the distance between each pair of cities. This is a classic optimization problem that requires a dynamic programming approach.

Detailed Explanation

To solve this problem, we can start by representing the distance matrix as an adjacency list or adjacency matrix. The goal is to find the minimum total time required to visit all cities and return to the starting city.

The algorithm works by initializing a 2D array dp of size n x n, where n is the number of cities, with all values set to infinity. Then, for each city i, we calculate the minimum time it takes to visit all cities starting from i. This is done by iterating through all possible paths and updating the dp array accordingly.

Here's a step-by-step breakdown of the solution:

  1. Initialize an adjacency list or adjacency matrix representing the distance between each pair of cities.
  2. Create a 2D array dp of size n x n, where n is the number of cities, with all values set to infinity.
  3. Iterate through each city i.
  4. For each city i, calculate the minimum time it takes to visit all cities starting from i. This can be done by iterating through all possible paths and updating the dp array accordingly.
  5. Return the minimum value in the last row of the dp array, which represents the minimum total time required to visit all cities and return to the starting city.

Time complexity: O(n^2) Space complexity: O(n^2)

Optimized Solutions

Java

View on GeeksforGeeks
public class MinTime {
    public static int minTime(int[][] graph) {
        int n = graph.length;
        int[] dp = new int[n];
        for (int i = 0; i < n; i++) {
            dp[i] = Integer.MAX_VALUE;
        }
        dp[0] = 0;
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (graph[j][i] != -1) {
                    dp[i] = Math.min(dp[i], dp[j] + graph[j][i]);
                }
            }
        }
        return dp[n-1];
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.