NeetCode #950LC-2629EasyJavaScript
← Back to All Problems#950 · #2629 · Function Composition(函数组合)
📌 Problem Statement & Constraints
Given an array of functions
functions, return a new function fn(x) whose result is the right-to-left composition of all of them. For example, [f, g, h] composes to f(g(h(x))).💡 Core Algorithmic Approaches
- Composition is right to left: the last function in the array is applied to
xfirst. - Implement by looping from
functions.length - 1down to 0, updatingx = functions[i](x). - When the array is empty the loop never runs and
xis returned unchanged — the identity function, as required. functions.reduceRight((acc, f) => f(acc), x)is the equivalent built-in form.
💻 Benchmark Python3 Implementation
var compose = function(functions) {
return function(x) {
// Apply right to left; an empty array returns x (the identity function)
for (let i = functions.length - 1; i >= 0; i--) {
x = functions[i](x);
}
return x;
};
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(k): one call per function.
💾 Space Complexity
O(1): only the running value is stored.
⚠️ Interview Pitfalls & Follow-ups
- Applying left to right: composition is right to left, since the mathematical
f(g(x))appliesgfirst. - Using
reduceinstead ofreduceRight: plainreducereverses the intended order. - Throwing on an empty array: the correct behaviour is to return
xunchanged.