Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

class Solution:
def jump(self, nums: List[int]) -> int:
"""
Greedy approach: At each position, jump to the farthest reachable index

Example: [2,3,1,1,4]
- From index 0 (value=2): can reach indices 1,2
- Greedy choice: Jump to index 1 (value=3) because it reaches farthest
- From index 1: can reach indices 2,3,4 (end)
- Answer: 2 jumps
"""

if len(nums) <= 1:
return 0

jumps = 0
current_end = 0 # End of current jump range
farthest = 0 # The farthest position we can reach

for i in range(len(nums) - 1):
# Update farthest position reachable
farthest = max(farthest, i + nums[i])

# If we've reached the end of current jump range
if i == current_end:
jumps += 1
current_end = farthest # Make the greedy choice

if current_end > len(nums) - 1:
break
return jumps
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
function jump(nums: number[]): number {
if (nums.length <= 1) return 0;

let jumps = 0;
let currentEnd = 0;
let farthest = 0;

for (let i = 0; i < nums.length - 1; i++) {
farthest = Math.max(farthest, i + nums[i]);

if (i === currentEnd) {
jumps++;
currentEnd = farthest;

if (currentEnd >= nums.length - 1) break;
}
}
return jumps;
};
17 changes: 17 additions & 0 deletions tests/test_150_questions_round_23/test_10_jump_game_ii_round_23.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import unittest
from src.my_project.interviews.top_150_questions_round_23\
.ex_10_jump_game_ii import Solution

class JumpIITestCase(unittest.TestCase):

def test_jump_i_first_case(self):
solution = Solution()
output = solution.jump(nums = [2,3,1,1,4])
target = 2
self.assertEqual(output, target)

def test_jump_i_second_case(self):
solution = Solution()
output = solution.jump(nums = [2,3,0,1,4])
target = 2
self.assertEqual(output, target)
Loading