Skip to the solution
MediumDSA14 min read

How do you solve the Jump Game?

264 views

The problem

Question presented to candidate: "You are given a list of non-negative integers. You start at index 0, and each value is the maximum jump length from that position. Write a Python function that returns whether you can reach the last index."

What a strong answer should cover:

  • The key observation: shorter jumps are allowed, so the reachable indices always form a prefix, and one number โ€” the farthest reach โ€” describes them.
  • The one-pass greedy: return false as soon as i > farthest, otherwise update farthest = max(farthest, i + nums[i]); O(n) time, O(1) space.
  • A correctness argument (the prefix / loop-invariant argument), not just the code.
  • The slower alternatives and why they lose: recursion (exponential) and the good[] DP (O(nยฒ)).
  • Python details: enumerate(nums) for index and value together, an early return True once the end is covered, and avoiding recursion because of the default recursion limit.
  • The Jump Game II follow-up (fewest jumps) as BFS levels.

Clarifying questions expected:

  • Is each value the maximum jump (shorter jumps allowed)?
  • Do you want only yes/no, or the fewest jumps?

Code / implementation expected: Yes โ€” can_jump(nums) -> bool in Python 3, one pass.

  • dsa
  • greedy
  • arrays

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonGreedy farthest-reach check (9 inputs)
PythonGreedy vs DP vs backward greedy: 2,000 random arrays and work counts
PythonFollow-up: Jump Game II (fewest jumps)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 108 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you clone a graph?

Continue