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.
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.
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.Path costs: [1, 2, 4, -1, 2], Max Jump: 2
dp[4] = 2.dp[2] = 4 + dp[4] = 6.dp[1] = 2 + dp[2] = 8.1 + dp[1] = 9.1 + dp[2] = 7.0 -> 2 -> 4.When a problem asks for "lexicographically smallest path," always consider if running your DP from right-to-left makes the tie-breaking logic simpler.