Minimum Cost to Reach Every Position - Problem

Imagine you're standing at the end of a line of n + 1 people (positions 0 to n), and you want to move forward to different positions. You start at position n (the very end) and want to calculate the minimum cost to reach every position from 0 to n-1.

Here's how the swapping works:

  • To move forward (swap with someone in front of you), you must pay them their specified cost
  • People behind you can swap with you for free (they want to move forward too!)

Given an array cost where cost[i] represents how much person i charges to swap places, return an array where answer[i] is the minimum total cost to reach position i.

The key insight is that once you pay to move forward, people behind you will help you move even further forward for free!

Input & Output

example_1.py โ€” Small Array
$ Input: cost = [1, 3, 2]
โ€บ Output: [6, 5, 2]
๐Ÿ’ก Note: To reach position 0: pay 1+3+2=6. To reach position 1: pay 3+2=5. To reach position 2: pay 2.
example_2.py โ€” Single Element
$ Input: cost = [5]
โ€บ Output: [5]
๐Ÿ’ก Note: Only one position to reach (position 0), and it costs 5 to swap with that person.
example_3.py โ€” Increasing Costs
$ Input: cost = [1, 2, 3, 4]
โ€บ Output: [10, 9, 7, 4]
๐Ÿ’ก Note: Position 0 costs 1+2+3+4=10. Position 1 costs 2+3+4=9. Position 2 costs 3+4=7. Position 3 costs 4.

Constraints

  • 1 โ‰ค cost.length โ‰ค 105
  • 1 โ‰ค cost[i] โ‰ค 106
  • You start at position n (end of line)
  • Positions are numbered from 0 to n

Visualization

Tap to expand
๐ŸŽต Concert Line StrategyP0Cost: $3P1Cost: $4P2Cost: $5P3Cost: $3YOUTo reach P0: Pay $3+$4+$5+$3 = $15Total: $15Total: $12Total: $8Total: $3Stage/Front of Concert โ†’
Understanding the Visualization
1
Start at Back
You begin at position n (end of line)
2
Pay to Advance
Pay each person their cost to swap places
3
Calculate Costs
Sum all costs from target position to end
Key Takeaway
๐ŸŽฏ Key Insight: Each position's minimum cost is simply the sum of all swap costs from that position to the end - this is exactly a suffix sum!
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 5
23.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen