Skip to the solution
MediumFrontend4 min read

What is memoization?

1.1k views

The problem

Question presented to candidate: "What is memoization, when does it actually help, and can you show it genuinely speeding up a repeated call?"

What a strong answer should cover:

  • Memoization caches a function's return value, keyed by its input arguments, so a repeated call with the SAME arguments returns instantly instead of recomputing.
  • It only produces correct results for pure functions β€” ones whose output depends only on their arguments, with no reliance on external mutable state and no side effects to skip.
  • It is a classic time-for-memory tradeoff: faster repeated calls, at the cost of holding cached results in memory for as long as the cache lives.
  • The cache key for multi-argument functions typically needs a resolver (e.g. JSON.stringify-ing the argument list, or a custom key function) β€” a plain single argument can often be used as the key directly.
  • Real verification: proving with a real timing measurement that a cached call is genuinely faster, not just assuming a Map lookup is fast.

Clarifying questions expected:

  • "Should the cache ever be cleared or bounded in size, or is an unbounded cache acceptable for this exercise?" (a strong candidate flags unbounded-cache memory growth as a real production concern)

Code / implementation expected: Yes β€” a short, genuinely runnable memoize implementation with a real, measured before/after timing comparison.

  • memoization

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read Β· 7 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptMemoize wrapper with a real measured speedup (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 51 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

How does WeakMap allow garbage collection of keys?

Continue