LeetCode 2642: Design Graph With Shortest Path Calculator Solution

Master LeetCode problem 2642 (Design Graph With Shortest Path Calculator), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2642. Design Graph With Shortest Path Calculator

Problem Explanation

Explanation

To solve this problem, we can use Dijkstra's algorithm to find the shortest path between two nodes in the graph. We will store the graph using an adjacency list and maintain a priority queue to keep track of the nodes with the minimum distance. We will also keep track of the minimum distance from the source node to each node in the graph.

  1. Initialize the distance array with infinity for all nodes except the source node which is set to 0.
  2. Create a priority queue and add the source node with distance 0 to it.
  3. While the priority queue is not empty, extract the node with the minimum distance.
  4. For each neighbor of the extracted node, update the distance if a shorter path is found and add the neighbor to the priority queue.
  5. Repeat the process until the priority queue is empty or the destination node is reached.
  6. Return the distance to the destination node if a path exists, otherwise return -1.

Time complexity:

  • The time complexity of Dijkstra's algorithm is O((V + E) log V) where V is the number of nodes and E is the number of edges in the graph.

Space complexity:

  • The space complexity is O(V) for storing the distances and O(V + E) for the adjacency list.

Solution Code

import java.util.*;

class Graph {
    Map<Integer, List<int[]>> adjList;
    
    public Graph(int n, int[][] edges) {
        adjList = new HashMap<>();
        for (int[] edge : edges) {
            adjList.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(new int[]{edge[1], edge[2]});
        }
    }
    
    public void addEdge(int[] edge) {
        adjList.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(new int[]{edge[1], edge[2]});
    }
    
    public int shortestPath(int node1, int node2) {
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
        Map<Integer, Integer> distances = new HashMap<>();
        
        pq.offer(new int[]{node1, 0});
        distances.put(node1, 0);
        
        while (!pq.isEmpty()) {
            int[] curr = pq.poll();
            int node = curr[0];
            int dist = curr[1];
            
            if (node == node2) {
                return dist;
            }
            
            if (adjList.containsKey(node)) {
                for (int[] neighbor : adjList.get(node)) {
                    int nextNode = neighbor[0];
                    int weight = neighbor[1];
                    int newDist = dist + weight;
                    
                    if (!distances.containsKey(nextNode) || newDist < distances.get(nextNode)) {
                        distances.put(nextNode, newDist);
                        pq.offer(new int[]{nextNode, newDist});
                    }
                }
            }
        }
        
        return -1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2642 (Design Graph With Shortest Path Calculator)?

This page provides optimized solutions for LeetCode problem 2642 (Design Graph With Shortest Path Calculator) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2642 (Design Graph With Shortest Path Calculator)?

The time complexity for LeetCode 2642 (Design Graph With Shortest Path Calculator) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2642 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2642 in Java, C++, or Python.

Back to LeetCode Solutions