Hackerrank step-perms
Challenge
The base cases for steps are 0, 1, 2, 4, and I add I recurse within step-perms’. The solution is correct for the test cases where the time limit does not exceed.
(defn step-perms [n]
"TOC: <20m
Complexity: "
(letfn [(step-perms' [n]
(cond
(= n 0) 0
(= n 1) 1
(= n 2) 2
(= n 3) 4
:else (+ (step-perms' (dec n))
(step-perms' (- n 2))
(step-perms' (- n 3)))))]
(mod (step-perms' n) 10000000007)))
(step-perms 5)
I memoize to avoid computing same results by storing values already computed in an atom map. All tests pass:
(defn step-perms
"TOC: <1h
Complexity: TBD"
[n]
(let [memoized-step-perms (atom {})]
(letfn [(memo-step-perms [k]
(if (get @memoized-step-perms k)
(get @memoized-step-perms k)
(let [result (step-perms' k)]
(swap! memoized-step-perms assoc k result) ;; looked up swap! online
result)))
(step-perms' [n]
(cond
(= n 0) 0
(= n 1) 1
(= n 2) 2
(= n 3) 4
:else (+ (memo-step-perms (dec n))
(memo-step-perms (- n 2))
(memo-step-perms (- n 3)))))]
(mod (step-perms' n) 10000000007))))
(step-perms 5)