Problem 55

Abstract / Summary

Determine if you can reach the end of an array by jumping according to the values at each position.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
26 lines | 618 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 41% (8+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Greedy
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 true without further processing, providing an early exit path.
  • When the jump lands before the last index, the target position is marked reachable in the reach array, 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.73 | σ = 1.35

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
59 links | 42 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Jump game | Leetcode #55 | Valley peak approach'
Techdose 13 mins
Jump game | Leetcode #55 | Valley peak approach
YouTube video 'Jump Game (LeetCode 55) | Full solution with animations and visuals | Greedy Algorithms'
Nikhil Lohia 19 mins
Jump Game (LeetCode 55) | Full solution with animations and visuals | Greedy Algorithms
YouTube video 'Jump Game - Leetcode 55 - Dynamic Programming (Python)'
Greg Hogg 9 mins
Jump Game - Leetcode 55 - Dynamic Programming (Python)
YouTube video 'Jump Game - LeetCode 55 Python'
Deepti Talesra 6 mins
Jump Game - LeetCode 55 Python
YouTube video 'Jump Game | (C++, Java, Python) |30 day Challenge | Day 25 | LeetCode #55'
Knowledge Center 15 mins
Jump Game | (C++, Java, Python) |30 day Challenge | Day 25 | LeetCode #55
YouTube video 'Jump Game - LeetCode 55 - JavaScript'
AlgoJS 6 mins
Jump Game - LeetCode 55 - JavaScript
YouTube video '[Java] Leetcode 55. Jump Game [DP Decision Making #3]'
Eric Programming 14 mins
[Java] Leetcode 55. Jump Game [DP Decision Making #3]
YouTube video '55. Jump Game | JavaScript | Recursion | Greedy Solution | O(n) | LeetCode Daily Challenge'
LeetCodeWithMonu 15 mins
55. Jump Game | JavaScript | Recursion | Greedy Solution | O(n) | LeetCode Daily Challenge
YouTube video 'Jump Game | Leetcode 55 | Live coding session 🔥🔥🔥'
Coding Decoded 8 mins
Jump Game | Leetcode 55 | Live coding session 🔥🔥🔥
YouTube video 'LeetCode 55 | Jump Game | Greedy Algorithm Explained (Java)'
Xavier Elon 6 mins
LeetCode 55 | Jump Game | Greedy Algorithm Explained (Java)
YouTube video 'Leetcode:- 55 Jump Game Telugu | Can You Reach the End? | Greedy Approach in Python | srkcodes'
Srk Codes 9 mins
Leetcode:- 55 Jump Game Telugu | Can You Reach the End? | Greedy Approach in Python | srkcodes
YouTube video 'Leetcode 55 - Jump Game (JAVA Solution Explained!)'
LC Bear 8 mins
Leetcode 55 - Jump Game (JAVA Solution Explained!)
YouTube video 'Daily Leetcode #1000: Dec 26, 2022 - 55. Jump Game'
Programming Live with Larry 6 mins
Daily Leetcode #1000: Dec 26, 2022 - 55. Jump Game
YouTube video 'LEETCODE OCTOBER DAILY CHALLENGE || 55. Jump Game || Explanation'
TechWithSaumya 9 mins
LEETCODE OCTOBER DAILY CHALLENGE || 55. Jump Game || Explanation
YouTube video 'Leetcode | Top Interview 150 | Medium | 55. Jump Game | Time: O(N) | Javascript'
Software Interviews Prep 12 mins
Leetcode | Top Interview 150 | Medium | 55. Jump Game | Time: O(N) | Javascript
YouTube video 'Jump Game Python Solution - LeetCode #55'
Professor Oakes 5 mins
Jump Game Python Solution - LeetCode #55
YouTube video '55. Jump Game | Leetcode | Medium | cpp | Java | Python | Javascript | Greedy'
Komal Pal 11 mins
55. Jump Game | Leetcode | Medium | cpp | Java | Python | Javascript | Greedy
YouTube video 'LeetCode 55: Jump Game | Python Solution | Greedy Algorithm'
Code Scribbler 8 mins
LeetCode 55: Jump Game | Python Solution | Greedy Algorithm
YouTube video 'Daily Leetcode #551: Oct 03, 2021 - 55. Jump Game'
Programming Live with Larry 6 mins
Daily Leetcode #551: Oct 03, 2021 - 55. Jump Game
YouTube video 'Microsoft Coding Interview Question | Leetcode 55 | Jump Game'
WorkWithGoogler 4 mins
Microsoft Coding Interview Question | Leetcode 55 | Jump Game
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

6 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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