Rod Cutting Problem in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to solve the rod cutting problem changes as the rod length grows.
Specifically, how the number of steps grows when we try all possible cuts to find the best price.
Analyze the time complexity of the following code snippet.
function rodCutting(prices: number[], n: number): number {
if (n <= 0) return 0;
let maxVal = -Infinity;
for (let i = 1; i <= n; i++) {
maxVal = Math.max(maxVal, prices[i - 1] + rodCutting(prices, n - i));
}
return maxVal;
}
This code tries every possible first cut and recursively solves the smaller rod to find the maximum price.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop tries all cut lengths from 1 to n.
- How many times: For each call with rod length n, it makes up to n recursive calls for smaller rods.
Each rod length n calls itself up to n times with smaller lengths, leading to many repeated calls.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | More than 1000 calls |
| 100 | More than 10^14 calls (very large) |
| 1000 | Extremely large, practically impossible without optimization |
Pattern observation: The number of calls grows very fast, much faster than just doubling.
Time Complexity: O(2^n)
This means the time needed doubles roughly with each additional unit of rod length, making it very slow for large n.
[X] Wrong: "The recursive solution runs in linear time because it just loops from 1 to n once."
[OK] Correct: Each recursive call itself makes many more calls, so the total work multiplies quickly, not just once.
Understanding this problem helps you see why recursion alone can be slow and why adding memory to save results is important.
"What if we store results of smaller rods to avoid repeated work? How would the time complexity change?"