Facebook Pixel

sum(1)(2)(3) Complexity and Optimization

Time and space complexity of the curried sum function.

sum(1)(2)(3) Complexity and Optimization

Time Complexity

O(n) where n is the number of chained calls. Each call creates a new function and performs one addition.

Space Complexity

O(n) where n is the number of chained calls. Each call creates a new closure. However, since each call returns a new function and the old one is no longer referenced, the GC can free the old closures. In practice, the space is O(1) (only the current closure is alive).

Tail Call Optimization

In theory, return sum(a + b) is a tail call. If the JS engine supported tail call optimization (TCO), the space would be O(1). However, most JS engines (V8, SpiderMonkey) do not implement TCO. So the call stack grows.

Stack Overflow

For a very long chain (e.g., 10,000 calls), the call stack may overflow. In practice, this is not an issue because nobody chains 10,000 calls.

Optimization

If performance is critical (it usually is not for this question), use a loop instead:

function sum(...nums) { return nums.reduce((a, b) => a + b, 0); } sum(1, 2, 3); // 6 (not curried, but O(n) with no closure overhead)

The Takeaway

Time: O(n). Space: O(n) (call stack) or O(1) (if GC frees old closures). TCO is not available in most JS engines. Stack overflow is possible for very long chains but impractical. If performance matters, use a non-curried reduce.

O(n) where n is the number of chained calls. Each call creates a new function and performs one addition. The total work is proportional to the number of calls.

O(n) for the call stack (each call adds a frame). However, since each call returns a new function and the old one is no longer referenced, the GC can free old closures. In practice, the space is close to O(1).

Most JS engines (V8, SpiderMonkey) do not implement tail call optimization, even though the ES6 spec includes it. So return sum(a + b) grows the call stack. For very long chains, this could cause stack overflow.

Yes, for a very long chain (e.g., 10,000+ calls). Each call adds a frame to the call stack. Without tail call optimization, the stack grows. In practice, nobody chains 10,000 calls, so this is not an issue.

If performance is critical, use a non-curried approach: function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }. This is O(n) with no closure overhead. But the curried version is for testing concept understanding, not production performance.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.