




Sponsored
Sponsored
This approach involves manually iterating over each element of the array using a for loop. For each element, we apply the provided function fn with the current element and its index as arguments. The result is then pushed into a new result array, which is returned at the end.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(n) for the resultant array.
In Java, a functional interface ArrFunction is used to define the transformation. The transformArray method iterates over the input array and applies the function, storing results in a list.
Another approach is to use recursion to apply the function to each element in the array. We define a recursive function that processes elements by moving from the start to the end of the array, applying transformations and constructing the result array.
Time Complexity: O(n)
Space Complexity: O(n) for result array and O(n) for function call stack.
1import java.util.ArrayList;
2import java.util.List;
3
4public class TransformArrayRecursive {
5    public static void transformArrayRecursive(int[] arr, List<Integer> result, int index, ArrFunction fn) {
6        if (index >= arr.length) return;
7        result.add(fn.apply(arr[index], index));
8        transformArrayRecursive(arr, result, index + 1, fn);
9    }
10
11    public static void main(String[] args) {
12        int[] arr = {1, 2, 3};
13        List<Integer> result = new ArrayList<>();
14        transformArrayRecursive(arr, result, 0, (n, i) -> n + 1);
15        System.out.println(result);
16    }
17}
18
19@FunctionalInterface
20interface ArrFunction {
21    int apply(int n, int i);
22}In the Java recursive approach, we use a similar recursive pattern where transformArrayRecursive applies the function to elements and forms the result list.