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

Leetcode #2361: Minimum Costs Using the Train Line

In this guide, we solve Leetcode #2361 Minimum Costs Using the Train Line 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

A train line going through a city has two routes, the regular route and the express route. Both routes go through the same n + 1 stops labeled from 0 to n.

Quick Facts

  • Difficulty: Hard
  • Premium: Yes
  • Tags: Array, Dynamic Programming

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

Input: regular = [1,6,9,5], express = [5,2,3,10], expressCost = 8 Output: [1,7,14,19] Explanation: The diagram above shows how to reach stop 4 from stop 0 with minimum cost. - Take the regular route from stop 0 to stop 1, costing 1. - Take the express route from stop 1 to stop 2, costing 8 + 2 = 10. - Take the express route from stop 2 to stop 3, costing 3. - Take the regular route from stop 3 to stop 4, costing 5. The total cost is 1 + 10 + 3 + 5 = 19. Note that a different route could be taken to reach the other stops with minimum cost.

Python Solution

class Solution: def minimumCosts( self, regular: List[int], express: List[int], expressCost: int ) -> List[int]: n = len(regular) f = [0] * (n + 1) g = [inf] * (n + 1) cost = [0] * n for i, (a, b) in enumerate(zip(regular, express), 1): f[i] = min(f[i - 1] + a, g[i - 1] + a) g[i] = min(f[i - 1] + expressCost + b, g[i - 1] + b) cost[i - 1] = min(f[i], g[i]) return cost

Complexity

The time complexity is O(n)O(n)O(n) and the space complexity is O(n)O(n)O(n), where nnn is the number of stations. The space complexity is O(n)O(n)O(n), where nnn is the number of stations.

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