Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2662: Minimum Cost of a Path With Special Roads

In this guide, we solve Leetcode #2662 Minimum Cost of a Path With Special Roads 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.

Leetcode

Problem Statement

You are given an array start where start = [startX, startY] represents your initial position (startX, startY) in a 2D space. You are also given the array target where target = [targetX, targetY] represents your target position (targetX, targetY).

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Graph, Array, 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.

Python Solution

class Solution: def minimumCost( self, start: List[int], target: List[int], specialRoads: List[List[int]] ) -> int: def dist(x1: int, y1: int, x2: int, y2: int) -> int: return abs(x1 - x2) + abs(y1 - y2) q = [(0, start[0], start[1])] vis = set() ans = inf while q: d, x, y = heappop(q) if (x, y) in vis: continue vis.add((x, y)) ans = min(ans, d + dist(x, y, *target)) for x1, y1, x2, y2, cost in specialRoads: heappush(q, (d + dist(x, y, x1, y1) + cost, x2, y2)) return ans

Complexity

The time complexity is O(n2×log⁡n)O(n^2 \times \log n)O(n2×logn), and the space complexity is O(n2)O(n^2)O(n2). The space complexity is O(n2)O(n^2)O(n2).

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.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy