Magicsheet logo

Coin Path

Hard
25%
Updated 8/1/2025

Asked by 1 Company

Coin Path

What is this problem about?

The Coin Path coding problem presents an array where each index has a "cost" in coins. If an index has a cost of -1, it's blocked. You start at the first index and must reach the last index. In each step, you can jump forward between 1 and max_jump positions. Your goal is to find the path that has the minimum total cost. If multiple paths have the same minimum cost, you must return the lexicographically smallest path.

Why is this asked in interviews?

Google uses the Coin Path interview question to test a candidate's ability to optimize for multiple criteria: first minimum cost, then lexicographical order. This problem is an excellent test of Dynamic Programming with path reconstruction. It requires careful state management to ensure the lexicographical requirement is met without significantly increasing time complexity.

Algorithmic pattern used

This is a Dynamic Programming problem. To handle the "lexicographically smallest" requirement efficiently, it is often easier to compute the DP backwards (from the end to the start).

  • dp[i] stores the minimum cost to reach the end starting from index i.
  • next_node[i] stores the index we jumped to from i to achieve that minimum cost.
  • Since we want the smallest path index-wise, when costs are tied, we pick the smaller index.

Example explanation

Path costs: [1, 2, 4, -1, 2], Max Jump: 2

  1. Start at the end: dp[4] = 2.
  2. From index 3: Cost is -1 (Blocked).
  3. From index 2: Can jump to 4. dp[2] = 4 + dp[4] = 6.
  4. From index 1: Can jump to 2 or 3. 3 is blocked. Jump to 2. dp[1] = 2 + dp[2] = 8.
  5. From index 0: Can jump to 1 or 2.
    • To 1: 1 + dp[1] = 9.
    • To 2: 1 + dp[2] = 7.
    • Min cost is 7, path: 0 -> 2 -> 4.

Common mistakes candidates make

  • Lexicographical Order: Not realizing that forward DP makes lexicographical ties harder to break correctly compared to backward DP.
  • Unreachable End: Not returning an empty list if there's no way to reach the final index.
  • Path Reconstruction: Forgetting to store the jump choices and only returning the cost.

Interview preparation tip

When a problem asks for "lexicographically smallest path," always consider if running your DP from right-to-left makes the tie-breaking logic simpler.

Similar Questions