




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 JavaScript, we manually iterate over the array using a simple for loop, applying the function to each element and collecting results in a new array, which is returned.
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.
1def transform_array_recursive(arr, fn, index=0, result=None):
2    if result is None:
3        result = []
4    if index == len(arr):
5        return result
6    result.append(fn(arr[index], index))
7    return transform_array_recursive(arr, fn, index + 1, result)
8
9# Example usage
10arr = [1, 2, 3]
11plus_one = lambda n, i: n + 1
12result = transform_array_recursive(arr, plus_one)
13print(result)The Python recursive method transform_array_recursive uses default parameters to iterate and transform the input array recursively.