C++ 0055.cpp
class Solution {
public:
bool canJump(vector<int>& nums) {
if (nums.size() == 1)
return true;
vector<char> reach(nums.size() + 1, false);
reach[0] = true;
for (auto i = 0; i < nums.size(); i++)
{
if (!reach[i])
continue;
for (auto j = 1; j <= nums[i]; j++)
{
if (i + j == nums.size() - 1)
return true;
if (i + j < nums.size() - 1)
reach[i + j] = true;
}
}
return false;
}
};
Difficulty
and has an acceptance rate of about 41% (8+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Greedy
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution::canJump method decides whether the last position of an integer array can be reached by jumping forward from the first element. Each element value indicates the maximum forward distance that can be taken from that index. The algorithm explores reachable positions iteratively and stops as soon as the end is confirmed reachable.
Early termination for trivial input
When the input contains only one element the destination is already satisfied, so the function returns true immediately.
if (nums.size() == 1)
return true;
This guard eliminates unnecessary work for the smallest possible array.
Reachability tracking structure
A dynamic array named reach records which indices are known to be reachable. It is sized one element larger than the input to simplify indexing and is initialized with false values, then the start position is marked reachable.
vector<char> reach(nums.size() + 1, false);
reach[0] = true;
Using char instead of bool reduces the overhead of bit-level packing and yields a compact, cache-friendly representation.
Main iteration over the input
The outer loop walks through each index of nums. The loop body is entered only for indices that have been marked reachable; unreachable positions are skipped instantly.
for (auto i = 0; i < nums.size(); i++)
{
if (!reach[i])
continue;
// inner processing follows
}
Skipping unreachable indices prevents needless inner-loop work, especially when large gaps of unreachable positions exist.
Exploration of jump possibilities
For a reachable index i, the inner loop enumerates every jump length from 1 up to the maximum allowed by nums[i]. Two important checks are performed inside this loop.
for (auto j = 1; j <= nums[i]; j++)
{
if (i + j == nums.size() - 1)
return true;
if (i + j < nums.size() - 1)
reach[i + j] = true;
}
- When the jump lands exactly on the last index, the function returns
truewithout further processing, providing an early exit path. - When the jump lands before the last index, the target position is marked reachable in the
reacharray, enabling subsequent outer-loop iterations to consider it.
Handling of boundary conditions
The code correctly treats the situation where a jump would overshoot the array bounds by limiting the inner loop to j <= nums[i] and checking i + j < nums.size() - 1 before marking a position. The early return condition i + j == nums.size() - 1 captures the exact arrival at the final element, while any attempt to go beyond the final element is ignored, preventing out-of-range accesses.
When an element contains 0, the inner loop executes zero times, leaving the current index without adding new reachable positions. This naturally models a dead-end scenario without extra conditional logic.
Implicit performance optimizations
The algorithm benefits from three implicit optimizations:
- The early return on reaching the last index eliminates further scanning of the array once success is proven.
- Skipping indices that are not reachable (
if (!reach[i]) continue;) reduces the number of inner-loop executions dramatically in cases where many positions cannot be accessed. - Storing reachability in a contiguous
vector<char>leverages spatial locality, allowing the CPU cache to prefetch successive entries efficiently during the outer loop.
These design choices collectively keep the execution focused on the subset of the array that actually contributes to a feasible path, avoiding unnecessary work and memory traffic.
ELI5 - Simplified Explanation
Imagine you are playing a fun game on a long path made of numbered squares. Each square has a special number on it that tells you exactly how many big hops you are allowed to take forward. You start at the very first square, and your goal is to reach the final square at the end of the path.
This code acts like a tiny helper that keeps a list to remember which squares you can land on. At the beginning, the helper marks your starting spot as a place you have successfully visited. Then, the helper starts looking at each square you are standing on. It checks the number on that square to see how far you can jump. For every jump you make, the helper marks the new destination square on its list so you know that the spot is reachable later.
As the helper moves along, it constantly checks if any of the jumps you make will land you right on the very last square of the path. If it sees that you can reach that final target, it gets very excited and confirms that the path is possible. If you finish looking at all the squares and still have not found a way to reach the end, then that specific path must be a bit too tricky to finish.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||||||
| WalkCCC | C++ | Java | Python | |||||||||||
| leetcode.ca | C++ | Java | Python | C# | Rust | JS | Go | TS | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||||
| Progiez | C++ | Java | Python | |||||||||||
| github | AdelDaniel | Dart | ||||||||||||
| aylei | Rust | |||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++ | |||||||||||||
| bujosa | Python | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| everthis | JS | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | C# | |||||||||||||
| fengvyi | C++ | |||||||||||||
| fpdjsns | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| gouthampradhan | Java | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JS | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| lennylxx | C | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| luangong | C++ | |||||||||||||
| MacJim | C++ | |||||||||||||
| martianoff | Scala | |||||||||||||
| qiyuangong | Java | |||||||||||||
| ruoru | Rust | |||||||||||||
| shreymehul | C# | |||||||||||||
| suxrobGM | C# | |||||||||||||
| varunu28 | Java | |||||||||||||
| vthwang | Java | |||||||||||||
| wisdompeak | C++ | |||||||||||||
| XiaotaoGuo | C++ | |||||||||||||
| yuanliu666 | Kotlin | |||||||||||||
| zfang399 | C++ | |||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||||
| WalkCCC | C++, Python, Java | |||||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||||
| Progiez | C++, Java, Python | |||||||||||||
| AdelDaniel | Dart | |||||||||||||
| aylei | Rust | |||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++, C++ | |||||||||||||
| bujosa | Python | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| everthis | JavaScript | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | C# | |||||||||||||
| fengvyi | C++ | |||||||||||||
| fpdjsns | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| gouthampradhan | Java | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JavaScript | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| lennylxx | C | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| luangong | C++ | |||||||||||||
| MacJim | C++ | |||||||||||||
| martianoff | Scala | |||||||||||||
| qiyuangong | Java | |||||||||||||
| ruoru | Rust | |||||||||||||
| shreymehul | C# | |||||||||||||
| suxrobGM | C# | |||||||||||||
| varunu28 | Java | |||||||||||||
| vthwang | Java | |||||||||||||
| wisdompeak | C++ | |||||||||||||
| XiaotaoGuo | C++ | |||||||||||||
| yuanliu666 | Kotlin | |||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 45: Jump Game II
- problem 1306: Jump Game III
- problem 1871: Jump Game VII
- problem 2297: Jump Game VIII
- problem 2617: Minimum Number of Visited Cells in a Grid
- problem 2789: Largest Element in an Array after Merge Operations
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality