2629. Function Composition
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.
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 <= 1000- all functions accept and return a single integer
Solutions
Solution 1
1 2 3 4 5 6 7 8 9 10 11 12 | |