




Sponsored
Sponsored
Iterative 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.
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.
This Java solution uses a list of Function objects. We iterate over the list from the last function to the first, applying each function to the input value.
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.
Time Complexity: O(n) where n is the number of functions.
Space Complexity: O(n) due to the recursive call stack.
1import java.util.List;
2import java.util.function.Function;
3
4public class FunctionComposition {
5    public static int recursiveCompose(List<Function<Integer, Integer>> functions, int index, int x) {
6        if (index < 0) return x;
7        x = functions.get(index).apply(x);
8        return recursiveCompose(functions, index - 1, x);
9    }
10
11    public static void main(String[] args) {
12        List<Function<Integer, Integer>> functions = List.of(
13            x -> x + 1,
14            x -> x * x,
15            x -> 2 * x
16        );
17        int x = 4;
18        System.out.println(recursiveCompose(functions, functions.size() - 1, x));
19    }
20}This Java solution uses recursion by calling each function, adjusting the index to apply to the composed results till no functions are left, indicating a finished composition.