Jump Game
LeetCode 55 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Move the goal left whenever i + nums[i] ≥ goal.
నేను Jump Game (LeetCode 55) ను ఇలా పరిష్కరించాను — Jump / Reachability ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Walk backwards keeping a 'goal' — the leftmost index known to reach the end. Any index that can jump to the goal becomes the new goal. If the goal reaches index 0, the start can make it.
Approach
- 1
goal = last index.
- 2
For i from right to left: if i + nums[i] ≥ goal, goal = i.
- 3
Return goal == 0.
నేను ఎలా పరిష్కరించాను
Greedy backward goalPythonO(n) time · O(1) space
class Solution:
def canJump(self, nums: List[int]) -> bool:
n = len(nums)
goal = n-1
i=n-1
while i>=0:
if nums[i]+i>=goal:
goal = i
i-=1
return goal==0Jump Game — తరచూ అడిగే ప్రశ్నలు
Jump Game వెనుక ఉన్న intuition ఏమిటి?
Walk backwards keeping a 'goal' — the leftmost index known to reach the end. Any index that can jump to the goal becomes the new goal. If the goal reaches index 0, the start can make it.
Jump Game (LeetCode 55) ను ఎలా పరిష్కరించాలి?
1. goal = last index. 2. For i from right to left: if i + nums[i] ≥ goal, goal = i. 3. Return goal == 0.
Jump Game యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(1). (Accepted approach: Greedy backward goal.)
Jump Game లో సాధారణ పొరపాట్లు ఏమిటి?
A zero only matters if nothing before it can jump past it.