




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.
using System.Collections.Generic;
public class Program
{
    public static List<int> TransformArray(int[] arr, Func<int, int, int> fn)
    {
        List<int> result = new List<int>();
        for (int i = 0; i < arr.Length; i++)
        {
            result.Add(fn(arr[i], i));
        }
        return result;
    }
    public static void Main()
    {
        int[] arr = { 1, 2, 3 };
        List<int> result = TransformArray(arr, (n, i) => n + 1);
        Console.WriteLine(String.Join(", ", result));
    }
}The C# implementation involves a method TransformArray that applies a lambda function to each element of the input array and stores 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.
1using System;
2using System.Collections.Generic;
3
4public class Program
5{
6    public static void TransformArrayRecursive(int[] arr, List<int> result, int index, Func<int, int, int> fn)
7    {
8        if (index >= arr.Length) return;
9        result.Add(fn(arr[index], index));
10        TransformArrayRecursive(arr, result, index + 1, fn);
11    }
12
13    public static void Main()
14    {
15        int[] arr = { 1, 2, 3 };
16        List<int> result = new List<int>();
17        TransformArrayRecursive(arr, result, 0, (n, i) => n + 1);
18        Console.WriteLine(String.Join(", ", result));
19    }
20}C# uses a recursive method TransformArrayRecursive to transform input using a lambda function. The result is collected in a list.