Quick revision
The short answer
The naive recursion for ways(n) = ways(n-1) + ways(n-2) + ways(n-3) recomputes the same subproblems again and again, so its time grows exponentially (bounded by O(3^n)). Memoization stores each answer the first time it is computed, which makes it O(n) time and O(n) space. An array memo beats a HashMap<Integer, Long> because it avoids boxing and hashing, recursive computeIfAbsent is broken on both HashMap and ConcurrentHashMap, and a bottom-up loop that keeps only the last three values needs O(1) space and no recursion at all; we use long, or BigInteger, because the counts overflow quickly.
What to remember
In this answer, we saw that the naive stair-climbing recursion is exponential because it recomputes the same subproblems, and memoization makes it O(n) time and O(n) space. An array memo is faster and smaller than a HashMap<Integer, Long>, which boxes every key and value. Calling computeIfAbsent recursively breaks: HashMap throws ConcurrentModificationException since Java 9, and ConcurrentHashMap can throw IllegalStateException or hang. A bottom-up loop that keeps the last three values needs O(1) space and no stack, and we use long, addExact or BigInteger because the counts overflow int at n = 37.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The naive recursion for ways(n) = ways(n-1) + ways(n-2) + ways(n-3) recomputes the same subproblems again and again, so its time grows exponentially (bounded by O(3^n)). Memoization stores each answer the first time it is computed, which makes it O(n) time and O(n) space. An array memo beats a HashMap<Integer, Long> because it avoids boxing and hashing, recursive computeIfAbsent is broken on both HashMap and ConcurrentHashMap, and a bottom-up loop that keeps only the last three values needs O(1) space and no recursion at all; we use long, or BigInteger, because the counts overflow quickly.
Why this question is asked
Memoization is the bridge between a simple recursive idea and dynamic programming, and it is one of the most useful techniques to recognise in real code: pricing rules, route counts and configuration resolution all have overlapping subproblems. Interviewers ask this in Java specifically because the language adds its own traps: boxing costs, integer overflow, and a computeIfAbsent shortcut that looks elegant and fails at runtime. In this answer, we will see why the naive recursion is slow, add a HashMap memo and an array memo, look closely at the computeIfAbsent pitfall, write the bottom-up version, and deal with overflow.
1The Naive Recursion and Why It Explodes
To reach step n, the last move was a step of 1, 2 or 3. So the number of ways to reach n is the sum of the ways to reach n - 1, n - 2 and n - 3. There is one way to stand at step 0 (do nothing) and no way to reach a negative step. That gives a direct recursive method.
Each call makes three more calls, and those make three more, so the call tree grows exponentially, bounded by O(3^n). The tighter growth rate is about 1.84^n, but the shape is the same. The reason is repetition: ways(40) calls ways(37) directly, but ways(39) calls it again, and ways(38) calls it again, and every one of those recomputes everything below. These are overlapping subproblems, and they are the signal that memoization will help.
2Adding a Memo: HashMap Versus Array
Memoization means caching the result of each subproblem the first time we compute it and returning the cached value on later calls. Since each ways(k) for k from 0 to n is computed once and each computation does constant work, the time becomes O(n), and the memo itself takes O(n) space. The recursion is still n levels deep.
Both are now fast, but the array is clearly better when the keys are small, dense integers. A HashMap<Integer, Long> boxes each key into an Integer and each value into a Long, allocates a node per entry, and hashes the key on every lookup, so it uses around 60 to 70 bytes per entry. The long[] uses 8 bytes per entry and a lookup is a single indexed read. Notice that we can use 0 as the "not computed" marker because every real answer for n >= 0 is at least 1.
3The computeIfAbsent Trap
Java 8 added computeIfAbsent, and it looks like the perfect memo: compute the value only if the key is missing. The natural recursive version is short and wrong.
The problem is that the mapping function, the lambda, itself calls computeIfAbsent on the same map, which inserts other keys while the outer call is still in the middle of inserting n. The Javadoc says the mapping function must not modify the map. Since Java 9, HashMap detects that its structure changed during the call and throws ConcurrentModificationException. ConcurrentHashMap locks the bin it is updating, so a recursive update to the same bin either throws IllegalStateException with the message Recursive update or, in some cases and older versions, spins or deadlocks. The fix is the explicit get, compute, put pattern shown earlier, or an array, or no memo at all with the bottom-up version below.
4Bottom-Up: No Memo Table, No Recursion
Once we see that ways(n) only depends on the three previous values, we can compute upwards from 0 and keep just those three. This is the bottom-up, or tabulation, form of dynamic programming.
| Version | Time | Extra space | Risk |
|---|---|---|---|
| Naive recursion | exponential, up to O(3^n) | O(n) stack | minutes of CPU by n = 40 |
HashMap memo | O(n) | O(n) boxed entries | boxing cost, deep recursion |
| Array memo | O(n) | O(n) longs | deep recursion for large n |
| Bottom-up loop | O(n) | O(1) | none, beyond overflow |
This version is O(n) time and O(1) space, and since it is a loop, it has no stack depth risk: waysBottomUp(100,000) runs fine, while the recursive memo versions would hit StackOverflowError somewhere in the tens of thousands, as each call still waits for the ones below it.
5Watching for Overflow
The counts grow by a factor of about 1.84 per step, so they leave the range of int very quickly: ways(36) is 2,082,876,103, just under Integer.MAX_VALUE, and ways(37) is 3,831,006,429, which an int silently wraps to a negative number. A long lasts until ways(73), roughly 1.3 x 10^19, which is beyond Long.MAX_VALUE. For larger n we either use BigInteger, or, as many interview variants ask, return the count modulo 1,000,000,007.
Math.addExact is a cheap safety net: it throws instead of producing a wrong number.
6Follow-up questions
How do you recognise that memoization will help?
Two signs together: the problem breaks into subproblems of the same shape, and the same subproblems come up repeatedly in the call tree. If we draw the calls for a small input and see the same argument many times, caching pays. If every subproblem is distinct, as in generating permutations, memoization saves nothing.
Is a memoized recursion the same as dynamic programming?
It is the top-down form of dynamic programming. Bottom-up DP computes subproblems in an order where dependencies are always ready, which removes recursion and often lets us keep only a few recent values. Top-down is easier to write when only some subproblems are needed; bottom-up is usually faster and safer for deep inputs.
Would you use a caching library for memoization in a service?
For an expensive pure function called with repeating arguments across requests, yes: Caffeine or Spring's @Cacheable gives size limits and expiry, which a plain map does not. For an algorithm's internal subproblems within one call, a local array or map is simpler and has no shared-state concerns.
7Conclusion
In this answer, we saw that the naive stair-climbing recursion is exponential because it recomputes the same subproblems, and memoization makes it O(n) time and O(n) space. An array memo is faster and smaller than a HashMap<Integer, Long>, which boxes every key and value. Calling computeIfAbsent recursively breaks: HashMap throws ConcurrentModificationException since Java 9, and ConcurrentHashMap can throw IllegalStateException or hang. A bottom-up loop that keeps the last three values needs O(1) space and no stack, and we use long, addExact or BigInteger because the counts overflow int at n = 37.
Open with
The naive version, ways of n equals ways of n minus 1 plus n minus 2 plus n minus 3, is exponential, bounded by 3 to the n, because the same subproblems are recomputed over and over: ways of 40 takes tens of billions of calls.
Then, if they want more
Memoization caches each result the first time, so every subproblem is computed once and it becomes O(n) time and O(n) space. In Java I would use a long array as the memo rather than a HashMap of Integer to Long, since the keys are small dense integers and the map boxes both keys and values and hashes on every lookup.
I would avoid the tempting recursive computeIfAbsent: the mapping function modifies the same map, which HashMap reports with ConcurrentModificationException since Java 9, and ConcurrentHashMap can throw IllegalStateException for a recursive update or even hang.
My preferred version is bottom-up: a loop from 1 to n that keeps only the last three values, which is O(n) time, O(1) space and has no stack depth risk at all. And I would use long, because the count passes the int range at n equals 37, and BigInteger or a modulus beyond n equals 72.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9, Java 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Explain how memoization changes a naive recursive solution such as counting the ways to...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/ec74f5ee04/