Skip to content

Commit 7461503

Browse files
author
Mauricio Klein
committed
Add solution for challenge #63
1 parent 44bcbef commit 7461503

File tree

6 files changed

+58
-0
lines changed

6 files changed

+58
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,4 @@
6262
- [x] [Challenge 60: Group anagrams](challenge-60/)
6363
- [x] [Challenge 61: Full Binary Tree](challenge-61/)
6464
- [x] [Challenge 62: Palindrome with maximum "k" deletions](challenge-62/)
65+
- [x] [Challenge 63: Jump to the end](challenge=63/)

challenge-63/Makefile

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
test:
2+
python test_*.py
3+
4+
.PHONY: test

challenge-63/README.md

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Jump to the end
2+
3+
This problem was asked by Facebook.
4+
5+
## Description
6+
7+
Starting at index 0, for an element n at index i, you are allowed to jump at most n indexes ahead.
8+
9+
Given a list of numbers, find the minimum number of jumps to reach the end of the list.
10+
11+
## Example
12+
13+
```
14+
Input:
15+
Input: [3, 2, 5, 1, 1, 9, 3, 4]
16+
Output: 2 (3 -> 5 -> 4)
17+
```

challenge-63/__init__.py

Whitespace-only changes.

challenge-63/solver.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"""
2+
Time complexity: O(n^2)
3+
Space complexity: O(n^2) (for the recursion tree)
4+
"""
5+
def jumps_to_end(nums):
6+
return helper(nums, 0, 0)
7+
8+
def helper(nums, acc_jumps, index):
9+
N = len(nums)
10+
11+
if index == N - 1:
12+
return acc_jumps
13+
14+
if index >= N:
15+
return float('inf')
16+
17+
best = float('inf')
18+
19+
for i in range(1, nums[index] + 1):
20+
best = min(best, helper(nums, acc_jumps + 1, index + i))
21+
22+
return best

challenge-63/test_solver.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import unittest
2+
from solver import jumps_to_end
3+
4+
class TestSolver(unittest.TestCase):
5+
def test_jumps_to_end(self):
6+
self.assertEqual(jumps_to_end([3, 2, 5, 1, 1, 9, 3, 4]), 2) # (3 -> 5 -> 4)
7+
self.assertEqual(jumps_to_end([1, 1, 1, 1, 1] ), 4) # (1 -> 1 -> 1 -> 1 -> 1)
8+
self.assertEqual(jumps_to_end([2, 2, 0, 1, 1] ), 3) # (2 -> 2 -> 1 -> 1)
9+
self.assertEqual(jumps_to_end([2] ), 0) # (2)
10+
11+
self.assertEqual(jumps_to_end([2, 0, 0, 1, 1]), float('inf')) # (No solution possible)
12+
13+
if __name__ == "__main__":
14+
unittest.main()

0 commit comments

Comments
 (0)