We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Function Composition

Difficulty: Easy


Problem Description

Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions. The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))). The function composition of an empty list of functions is the identity function f(x) = x.


Key Insights

  • Function composition requires evaluating functions in reverse order.
  • An empty list of functions should return the identity function.
  • Each function operates on a single integer input and returns a single integer output.

Space and Time Complexity

Time Complexity: O(n), where n is the number of functions in the array. Space Complexity: O(1), as we do not use any additional data structures that grow with input size.


Solution

To solve the problem, we will create a new function that takes an integer input. This function will iterate through the array of functions in reverse order, applying each function to the result of the previous function. If the functions array is empty, it will simply return the input value as the identity function.


Code Solutions

def compose(functions):
    def fn(x):
        for f in reversed(functions):
            x = f(x)
        return x
    return fn
← Back to All Questions