Skip to main content

Jump Game

LeetCode 55 | Difficulty: Medium​

Medium

Problem Description​

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.

Example 1:

Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

Constraints:

- `1 <= nums.length <= 10^4`

- `0 <= nums[i] <= 10^5`

Topics: Array, Dynamic Programming, Greedy


Approach​

Dynamic Programming​

Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.

When to use

Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).

Greedy​

At each step, make the locally optimal choice. The challenge is proving the greedy choice leads to a global optimum. Look for: can I sort by some criterion? Does choosing the best option now ever hurt future choices?

When to use

Interval scheduling, activity selection, minimum coins (certain denominations), Huffman coding.


Solutions​

Solution 1: C# (Best: 116 ms)​

MetricValue
Runtime116 ms
MemoryN/A
Date2018-04-30
Solution
public class Solution {
public bool CanJump(int[] nums) {
int n=nums.Length;
int reach=0;
for (int i = 0; i < n && i<=reach; i++)
{
reach = Math.Max(i+nums[i], reach);
if(reach>=n-1) return true;
}
return false;
}
}
πŸ“œ 2 more C# submission(s)

Submission (2018-04-30) β€” 116 ms, N/A​

public class Solution {
public bool CanJump(int[] nums) {
int n=nums.Length;
int reach=0;
for (int i = 0; i < n-1 && i<=reach; i++)
{
reach = Math.Max(i+nums[i], reach);
if(reach>=n-1) return true;
}
return reach>=n-1;
}
}

Submission (2018-03-08) β€” 124 ms, N/A​

public class Solution {
public bool CanJump(int[] nums) {
int n=nums.Length;
int reach=0;
for (int i = 0; i < n-1 && i<=reach; i++)
{
reach = Math.Max(i+nums[i], reach);
if(reach>=n-1) return true;
}
return reach>=n-1;
}
}

Complexity Analysis​

ApproachTimeSpace
Dynamic Programming$O(n)$$O(n)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
  • Consider if you can reduce space by only keeping the last row/few values.