Jump Game
LeetCode 55 | Difficulty: Mediumβ
MediumProblem 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.
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?
Interval scheduling, activity selection, minimum coins (certain denominations), Huffman coding.
Solutionsβ
Solution 1: C# (Best: 116 ms)β
| Metric | Value |
|---|---|
| Runtime | 116 ms |
| Memory | N/A |
| Date | 2018-04-30 |
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β
| Approach | Time | Space |
|---|---|---|
| Dynamic Programming | $O(n)$ | $O(n)$ |
Interview Tipsβ
- 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.