656. Coin Path
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for a path from index 1 to index n in an array coins with the minimum total cost. The cost of visiting an index is given by the value at that index. From index i, we can jump to any index j within the range [i+1, i+maxJump]. Some indices are invalid (marked with -1) and cannot be visited. If multiple paths yield the same minimum cost, we must choose the one that is lexicographically smallest. If the destination is unreachable, we should return an empty array.
Solution
Coin Path in Python
class Solution:
def cheapestJump(self, coins: List[int], maxJump: int) -> List[int]:
n = len(coins)
if n == 0 or coins[n-1] == -1:
return []
# dp[i] stores the minimum cost to reach the end from index i.
# Using float('inf') to represent an unreachable state.
dp = [float('inf')] * n
# next_idx[i] stores the next index to jump to from i on the optimal path.
next_idx = [-1] * n
# Base case: the last element.
dp[n - 1] = coins[n - 1]
# Iterate backwards from the second to last element.
for i in range(n - 2, -1, -1):
if coins[i] == -1:
continue # Cannot jump from this square.
# Find the best next jump in the range [i+1, min(n-1, i+maxJump)]
best_next = -1
for j in range(i + 1, min(n, i + maxJump + 1)):
if dp[j] != float('inf'):
# To find the best path, we need to minimize (cost, lexicographical_path).
# This simplifies to minimizing (dp[j], path_from_j) for the next step.
# Path comparison for path_from_j and path_from_best_next simplifies to comparing j and best_next.
if best_next == -1 or dp[j] < dp[best_next] or (dp[j] == dp[best_next] and j < best_next):
best_next = j
if best_next != -1:
dp[i] = coins[i] + dp[best_next]
next_idx[i] = best_next
# If dp[0] is inf, it's impossible to reach the end.
if dp[0] == float('inf'):
return []
# Reconstruct the path.
path = []
curr = 0
while curr != -1:
path.append(curr + 1) # Convert to 1-based index.
curr = next_idx[curr]
return path
Coin Path in Java
class Solution {
public List<Integer> cheapestJump(int[] coins, int maxJump) {
int n = coins.length;
List<Integer> emptyList = new ArrayList<>();
if (n == 0) {
return emptyList;
}
// dp[i] stores the minimum cost to reach the end from index i.
// Using -1 to represent an unreachable state, since costs are non-negative.
long[] dp = new long[n];
Arrays.fill(dp, -1);
// next_idx[i] stores the next index to jump to from i on the optimal path.
int[] next_idx = new int[n];
Arrays.fill(next_idx, -1);
// Base case: the last element.
if (coins[n - 1] != -1) {
dp[n - 1] = coins[n - 1];
}
// Iterate backwards from the second to last element.
for (int i = n - 2; i >= 0; i--) {
if (coins[i] == -1) {
continue; // Cannot jump from this square.
}
int best_next = -1;
// Find the best next jump.
for (int j = i + 1; j < n && j <= i + maxJump; j++) {
if (dp[j] == -1) {
continue; // Destination is unreachable from j.
}
// To find the best path, we need to minimize (cost, lexicographical_path).
// This simplifies to minimizing (dp[j], path_from_j) for the next step.
// The path comparison boils down to comparing the first elements, so we minimize (dp[j], j).
if (best_next == -1 || dp[j] < dp[best_next] || (dp[j] == dp[best_next] && isLexicographicallySmaller(j, best_next, next_idx))) {
best_next = j;
}
}
if (best_next != -1) {
dp[i] = (long)coins[i] + dp[best_next];
next_idx[i] = best_next;
}
}
// If dp[0] is -1, it's impossible to reach the end.
if (dp[0] == -1) {
return emptyList;
}
// Reconstruct the path.
List<Integer> path = new ArrayList<>();
int curr = 0;
while (curr != -1) {
path.add(curr + 1); // Convert to 1-based index.
curr = next_idx[curr];
}
return path;
}
private boolean isLexicographicallySmaller(int i, int j, int[] next_idx) {
while (i != -1 && j != -1) {
if (i < j) return true;
if (j < i) return false;
i = next_idx[i];
j = next_idx[j];
}
return i != -1; // Should not happen if both paths end properly
}
}
Coin Path in C++
class Solution {
public:
vector<int> cheapestJump(vector<int>& coins, int maxJump) {
int n = coins.size();
if (n == 0) {
return {};
}
// dp[i] stores the minimum cost to reach the end from index i.
// Using -1 to represent an unreachable state.
vector<long> dp(n, -1);
// next_idx[i] stores the next index to jump to from i on the optimal path.
vector<int> next_idx(n, -1);
// Base case: the last element.
if (coins[n - 1] != -1) {
dp[n - 1] = coins[n - 1];
}
// Iterate backwards from the second to last element.
for (int i = n - 2; i >= 0; --i) {
if (coins[i] == -1) {
continue; // Cannot jump from this square.
}
int best_next = -1;
// Find the best next jump.
for (int j = i + 1; j < n && j <= i + maxJump; ++j) {
if (dp[j] == -1) {
continue; // Destination is unreachable from j.
}
// To find the best path, we need to minimize (cost, lexicographical_path).
// This simplifies to minimizing (dp[j], j) for the next step.
if (best_next == -1 || dp[j] < dp[best_next] || (dp[j] == dp[best_next] && j < next_idx[best_next])) {
best_next = j;
}
}
if (best_next != -1) {
dp[i] = (long)coins[i] + dp[best_next];
next_idx[i] = best_next;
}
}
// If dp[0] is -1, it's impossible to reach the end.
if (dp[0] == -1) {
return {};
}
// Reconstruct the path.
vector<int> path;
int curr = 0;
while (curr != -1) {
path.push_back(curr + 1); // Convert to 1-based index.
curr = next_idx[curr];
}
return path;
}
};
Coin Path in TypeScript
function cheapestJump(coins: number[], maxJump: number): number[] {
const n = coins.length;
if (n === 0) {
return [];
}
// dp[i] stores the minimum cost to reach the end from index i.
// Using -1 to represent an unreachable state.
const dp: number[] = new Array(n).fill(-1);
// next_idx[i] stores the next index to jump to from i on the optimal path.
const next_idx: number[] = new Array(n).fill(-1);
// Base case: the last element.
if (coins[n - 1] !== -1) {
dp[n - 1] = coins[n - 1];
}
// Helper for lexicographical comparison of paths starting from i and j
const isLexicographicallySmaller = (i: number, j: number): boolean => {
while (i !== -1 && j !== -1) {
if (i < j) return true;
if (j < i) return false;
i = next_idx[i];
j = next_idx[j];
}
return i !== -1; // Should not be reached given problem constraints
};
// Iterate backwards from the second to last element.
for (let i = n - 2; i >= 0; i--) {
if (coins[i] === -1) {
continue; // Cannot jump from this square.
}
let best_next = -1;
// Find the best next jump.
for (let j = i + 1; j < n && j <= i + maxJump; j++) {
if (dp[j] === -1) {
continue; // Destination is unreachable from j.
}
if (best_next === -1 || dp[j] < dp[best_next] ||
(dp[j] === dp[best_next] && isLexicographicallySmaller(j, best_next))) {
best_next = j;
}
}
if (best_next !== -1) {
dp[i] = coins[i] + dp[best_next];
next_idx[i] = best_next;
}
}
// If dp[0] is -1, it's impossible to reach the end.
if (dp[0] === -1) {
return [];
}
// Reconstruct the path.
const path: number[] = [];
let curr = 0;
while (curr !== -1) {
path.push(curr + 1); // Convert to 1-based index.
curr = next_idx[curr];
}
return path;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.