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.
You may assume each function in the array accepts one integer as input and returns one integer as output.
Example 1:
Input: functions = [x => x + 1, x => x * x, x => 2 * x], x = 4 Output: 65 Explanation: Evaluating from right to left ... Starting with x = 4. 2 * (4) = 8 (8) * (8) = 64 (64) + 1 = 65
Example 2:
Input: functions = [x => 10 * x, x => 10 * x, x => 10 * x], x = 1 Output: 1000 Explanation: Evaluating from right to left ... 10 * (1) = 10 10 * (10) = 100 10 * (100) = 1000
Example 3:
Input: functions = [], x = 42 Output: 42 Explanation: The composition of zero functions is the identity function
Constraints:
-1000 <= x <= 10000 <= functions.length <= 1000Iterative Approach: In this approach, we compose the functions iteratively from the last function to the first. This is because function composition works in reverse order, i.e., f(g(h(x))) means first apply h, then g, and finally f. We start with the input value x and apply each function in the function list from right to left.
This C solution defines an array of function pointers and iterates over the functions from right to left, applying each one to the initial input. Each function is applied in turn, modifying the input, and the final result is returned.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) where n is the number of functions.
Space Complexity: O(1) since we are using a fixed amount of extra space.
Recursive Approach: This approach encapsulates the recursive function composition in a way that it applies the last function first and makes a recursive call to apply the rest. We either call the next composed function recursively until the base case, i.e., no functions left, is reached, or upon an empty function list, return the input as it is simply the identity function.
This C implementation defines a recursive function which applies the last function in the array and then calls itself with the remaining functions one less in length, composed into a single final result.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) where n is the number of functions.
Space Complexity: O(n) due to the recursive call stack.
| Approach | Complexity |
|---|---|
| Iterative Right-to-Left Composition | Time Complexity: O(n) where n is the number of functions. |
| Recursive Right-to-Left Composition | Time Complexity: O(n) where n is the number of functions. |
How many LeetCode problems should you solve? #leetcode #techinterview #developer #softwareengineer • CrioDo • 304,679 views views
Watch 9 more video solutions →Practice Function Composition with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor