3123. Find Edges in Shortest Paths LeetCode Solution

In this guide, you will get 3123. Find Edges in Shortest Paths LeetCode Solution with the best time and space complexity. The solution to Find Edges in Shortest Paths problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Find Edges in Shortest Paths solution in C++
  4. Find Edges in Shortest Paths solution in Java
  5. Find Edges in Shortest Paths solution in Python
  6. Additional Resources
3123. Find Edges in Shortest Paths LeetCode Solution image

Problem Statement of Find Edges in Shortest Paths

You are given an undirected weighted graph of n nodes numbered from 0 to n – 1. The graph consists of m edges represented by a 2D array edges, where edges[i] = [ai, bi, wi] indicates that there is an edge between nodes ai and bi with weight wi.
Consider all the shortest paths from node 0 to node n – 1 in the graph. You need to find a boolean array answer where answer[i] is true if the edge edges[i] is part of at least one shortest path. Otherwise, answer[i] is false.
Return the array answer.
Note that the graph may not be connected.

Example 1:

Input: n = 6, edges = [[0,1,4],[0,2,1],[1,3,2],[1,4,3],[1,5,1],[2,3,1],[3,5,3],[4,5,2]]
Output: [true,true,true,false,true,true,true,false]
Explanation:
The following are all the shortest paths between nodes 0 and 5:

The path 0 -> 1 -> 5: The sum of weights is 4 + 1 = 5.
The path 0 -> 2 -> 3 -> 5: The sum of weights is 1 + 1 + 3 = 5.
The path 0 -> 2 -> 3 -> 1 -> 5: The sum of weights is 1 + 1 + 2 + 1 = 5.

See also  525. Contiguous Array LeetCode Solution

Example 2:

Input: n = 4, edges = [[2,0,1],[0,1,1],[0,3,4],[3,2,2]]
Output: [true,false,false,true]
Explanation:
There is one shortest path between nodes 0 and 3, which is the path 0 -> 2 -> 3 with the sum of weights 1 + 2 = 3.

Constraints:

2 <= n <= 5 * 104
m == edges.length
1 <= m <= min(5 * 104, n * (n – 1) / 2)
0 <= ai, bi < n
ai != bi
1 <= wi <= 105
There are no repeated edges.

Complexity Analysis

  • Time Complexity: O(|V|\log |E|)
  • Space Complexity: O(n)

3123. Find Edges in Shortest Paths LeetCode Solution in C++

class Solution {
 public:
  // Similar to 2203. Minimum Weighted Subgraph With the Required Paths
  vector<bool> findAnswer(int n, vector<vector<int>>& edges) {
    vector<bool> ans;
    vector<vector<pair<int, int>>> graph(n);

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      const int w = edge[2];
      graph[u].emplace_back(v, w);
      graph[v].emplace_back(u, w);
    }

    const vector<int> from0 = dijkstra(graph, 0);
    const vector<int> from1 = dijkstra(graph, n - 1);

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      const int w = edge[2];
      ans.push_back(from0[u] + w + from1[v] == from0[n - 1] ||
                    from0[v] + w + from1[u] == from0[n - 1]);
    }

    return ans;
  }

 private:
  static constexpr int kMax = 1'000'000'000;

  vector<int> dijkstra(const vector<vector<pair<int, int>>>& graph, int src) {
    vector<int> dist(graph.size(), kMax);

    dist[src] = 0;
    using P = pair<int, int>;  // (d, u)
    priority_queue<P, vector<P>, greater<>> minHeap;
    minHeap.emplace(dist[src], src);

    while (!minHeap.empty()) {
      const auto [d, u] = minHeap.top();
      minHeap.pop();
      if (d > dist[u])
        continue;
      for (const auto& [v, w] : graph[u])
        if (d + w < dist[v]) {
          dist[v] = d + w;
          minHeap.emplace(dist[v], v);
        }
    }

    return dist;
  }
};
/* code provided by PROGIEZ */

3123. Find Edges in Shortest Paths LeetCode Solution in Java

class Solution {
  // Similar to 2203. Minimum Weighted Subgraph With the Required Paths
  public boolean[] findAnswer(int n, int[][] edges) {
    boolean[] ans = new boolean[edges.length];
    List<Pair<Integer, Integer>>[] graph = new List[n];

    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      final int w = edge[2];
      graph[u].add(new Pair<>(v, w));
      graph[v].add(new Pair<>(u, w));
    }

    int[] from0 = dijkstra(graph, 0);
    int[] from1 = dijkstra(graph, n - 1);

    for (int i = 0; i < edges.length; ++i) {
      final int u = edges[i][0];
      final int v = edges[i][1];
      final int w = edges[i][2];
      ans[i] = from0[u] + w + from1[v] == from0[n - 1] || //
               from0[v] + w + from1[u] == from0[n - 1];
    }

    return ans;
  }

  private static int kMax = 1_000_000_000;

  private int[] dijkstra(List<Pair<Integer, Integer>>[] graph, int src) {
    int[] dist = new int[graph.length];
    Arrays.fill(dist, kMax);

    dist[src] = 0;
    Queue<Pair<Integer, Integer>> minHeap =
        new PriorityQueue<>(Comparator.comparing(Pair::getKey)) {
          { offer(new Pair<>(dist[src], src)); } // (d, u)
        };

    while (!minHeap.isEmpty()) {
      final int d = minHeap.peek().getKey();
      final int u = minHeap.poll().getValue();
      if (d > dist[u])
        continue;
      for (Pair<Integer, Integer> pair : graph[u]) {
        final int v = pair.getKey();
        final int w = pair.getValue();
        if (d + w < dist[v]) {
          dist[v] = d + w;
          minHeap.offer(new Pair<>(dist[v], v));
        }
      }
    }

    return dist;
  }
};
// code provided by PROGIEZ

3123. Find Edges in Shortest Paths LeetCode Solution in Python

class Solution:
  # Similar to 2203. Minimum Weighted Subgraph With the Required Paths
  def findAnswer(self, n: int, edges: list[list[int]]) -> list[bool]:
    graph = [[] for _ in range(n)]

    for u, v, w in edges:
      graph[u].append((v, w))
      graph[v].append((u, w))

    from0 = self._dijkstra(graph, 0)
    from1 = self._dijkstra(graph, n - 1)
    return [from0[u] + w + from1[v] == from0[-1] or
            from0[v] + w + from1[u] == from0[-1]
            for u, v, w in edges]

  def _dijkstra(
      self,
      graph: list[list[tuple[int, int]]],
      src: int,
  ) -> list[int]:
    dist = [10**9] * len(graph)

    dist[src] = 0
    minHeap = [(dist[src], src)]  # (d, u)

    while minHeap:
      d, u = heapq.heappop(minHeap)
      if d > dist[u]:
        continue
      for v, w in graph[u]:
        if d + w < dist[v]:
          dist[v] = d + w
          heapq.heappush(minHeap, (dist[v], v))

    return dist
# code by PROGIEZ

Additional Resources

See also  1471. The k Strongest Values in an Array LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.