Skip to content

Commit d4659ed

Browse files
author
Gonzalo Diaz
committed
[Hacker Rank] Interview Preparation Kit: Recursion: Davis' Staircase. Clean code improvements and new generalized solution.
1 parent db75212 commit d4659ed

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

src/hackerrank/interview_preparation_kit/recursion_and_backtracking/ctci_recursive_staircase.py

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,38 @@
44

55
from typing import Dict
66

7+
TOP_LIMIT = 10 ** 10 + 7
8+
STEPS_LIMIT = 3
79

8-
def step_perms_comput_with_cache(n_steps: int, cache: Dict[int, int]) -> int:
10+
11+
def step_perms_comput_with_cache(
12+
n_steps: int,
13+
cache: Dict[int, int],
14+
steps_limit: int) -> int:
15+
16+
# Base cases
917
if 0 <= n_steps <= 2:
1018
return n_steps
11-
if n_steps == 3:
12-
return 4
1319

1420
result = 0
15-
for i in range(1, 4):
16-
if n_steps - i not in cache:
17-
cache[n_steps - i] = step_perms_comput_with_cache(n_steps - i, cache)
21+
for i in range(1, min(steps_limit, n_steps) + 1):
22+
search_key: int = n_steps - i
23+
24+
if search_key not in cache:
25+
cache[search_key] = step_perms_comput_with_cache(
26+
search_key,
27+
cache,
28+
steps_limit
29+
)
1830

1931
result += cache[n_steps - i]
2032

21-
return result
33+
# if n_steps <= steps_limit:
34+
# result += 1
35+
36+
return (result + 1) if n_steps <= steps_limit else result
2237

2338

2439
def step_perms(n_steps: int) -> int:
2540
initial_cache: Dict[int, int] = {}
26-
return step_perms_comput_with_cache(n_steps, initial_cache) % (10 ** 10 + 7)
41+
return step_perms_comput_with_cache(n_steps, initial_cache, STEPS_LIMIT) % TOP_LIMIT

0 commit comments

Comments
 (0)