InterviewPrepKit

Home / Coding / Greedy

Jump Game

medium Original β†—
Solving tips
  • Key insight: reachable indices form a contiguous prefix [0, farthest], so collapse all state into one number β€” the farthest reachable index.
  • Scan left to right; if index i ever exceeds farthest you've hit an unreachable gap and can return False immediately.
  • At each reachable i, extend farthest = max(farthest, i + nums[i]); return True once farthest reaches the last index.
  • Target O(n) time and O(1) space; don't panic on seeing a 0 β€” it's only fatal if no earlier jump vaults over it, which the frontier check handles.

Problem

You are given an integer array nums. You start at index 0. Each nums[i] is the maximum jump length from index i β€” from i you may step to any index in i+1, i+2, ..., i+nums[i] (as long as it stays in bounds). Return True if you can reach the last index, False otherwise.

Examples

  • nums = [2,3,1,1,4] β†’ True β€” jump 0β†’1 (length 1), then 1β†’4 (length 3), landing on the last index.
  • nums = [3,2,1,0,4] β†’ False β€” every route stalls at index 3, whose value 0 allows no further jump; index 4 is unreachable.
  • nums = [0] β†’ True β€” you are already on the last (and only) index.

Constraints

  • 1 <= len(nums) <= 10^4
  • 0 <= nums[i] <= 10^5

An O(n) scan is expected; the 0 values are the traps that make it non-trivial.

Think about it first

Hint 1 You do not need to know how you get somewhere, only whether it is reachable. As you move left to right, what single number summarizes everything reachable so far?
Hint 2 Track the farthest index reachable. At each position i, first check: is i itself within the current reach? If not, you are stuck and can never proceed.
Hint 3 If i is reachable, update the frontier to max(farthest, i + nums[i]). If the frontier ever reaches or passes the last index, return True.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.