Skip to the editor
JSGroundwork
JSGroundwork handwritten · web dev
←Back to Basic recursion

Ready to read

JSJavaScript⑂Git◎Interview prepΣDSA in JSSDSystem Design
More topics15›
</>HTML{ }CSS⚛ReactNNext.jsNeNest.jsTSTypeScriptNoNode.js🐳DockerDBSQL & Databases✓Testing🔒Web Security☁Cloud & DevOps◈GraphQL◆Redis☸Kubernetes
☰‹›
Description
All topics›JavaScript›Basic recursion

Fibonacci with Memoisation

beginnerlayer B10 · Basic recursion5 tests

Return the nth Fibonacci number, where fib(0) = 0, fib(1) = 1 and every later value is the sum of the two before it.

  • The naive recursion fib(n-1) + fib(n-2) is O(2^n): each call spawns two more, so the call tree roughly doubles at every level and the same subproblems are recomputed over and over — fib(40) already takes billions of calls
  • Memoise it: cache each result the first time you compute it. Every value is then computed once, making it O(n)
  • The tests call fib(78), which is unreachable without a cache
  • Answers stay exact integers up to fib(78)

Stuck?

All exercisesPlayground
1234567891011121314
loading the editor…

Nothing yet — hit Run and whatever you log shows up here.

Submit to see how you did.

⌘/Ctrl + Enter run⌘/Ctrl + S save⌘/Ctrl + / comment⌘/Ctrl + F find/replace⌘/Ctrl + D select next matchAlt + click multi-cursorTab indent · ⇧Tab outdentEsc leave fullscreen