Leetcode #2699: Modify Graph Edge Weights
In this guide, we solve Leetcode #2699 Modify Graph Edge Weights in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an undirected weighted connected graph containing n nodes labeled from 0 to n - 1, and an integer array edges where edges[i] = [ai, bi, wi] indicates that there is an edge between nodes ai and bi with weight wi. Some edges have a weight of -1 (wi = -1), while others have a positive weight (wi > 0).
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Graph, Shortest Path, Heap (Priority Queue)
Intuition
We need to repeatedly access the smallest or largest element as the input changes.
A heap provides fast insertions and removals while keeping order.
Approach
Push candidates into the heap as you scan, and pop when you need the best element.
Keep the heap size bounded if the problem requires a top-k structure.
Steps:
- Push candidates into a heap.
- Pop the best candidate when needed.
- Maintain heap size or invariants.
Example
Input: n = 5, edges = [[4,1,-1],[2,0,-1],[0,3,-1],[4,3,-1]], source = 0, destination = 1, target = 5
Output: [[4,1,1],[2,0,1],[0,3,3],[4,3,1]]
Explanation: The graph above shows a possible modification to the edges, making the distance from 0 to 1 equal to 5.
Python Solution
class Solution:
def modifiedGraphEdges(
self, n: int, edges: List[List[int]], source: int, destination: int, target: int
) -> List[List[int]]:
def dijkstra(edges: List[List[int]]) -> int:
g = [[inf] * n for _ in range(n)]
for a, b, w in edges:
if w == -1:
continue
g[a][b] = g[b][a] = w
dist = [inf] * n
dist[source] = 0
vis = [False] * n
for _ in range(n):
k = -1
for j in range(n):
if not vis[j] and (k == -1 or dist[k] > dist[j]):
k = j
vis[k] = True
for j in range(n):
dist[j] = min(dist[j], dist[k] + g[k][j])
return dist[destination]
inf = 2 * 10**9
d = dijkstra(edges)
if d < target:
return []
ok = d == target
for e in edges:
if e[2] > 0:
continue
if ok:
e[2] = inf
continue
e[2] = 1
d = dijkstra(edges)
if d <= target:
ok = True
e[2] += target - d
return edges if ok else []
Complexity
The time complexity is , and the space complexity is , where is the number of points in the graph. The space complexity is , where is the number of points in the graph.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.