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.