




Sponsored
Sponsored
This approach simply involves directly iterating through the elements of the array using a loop, starting with the initial value. For each element, apply the reducer function and update the accumulated result. This approach mimics the behavior of the JavaScript Array.reduce method.
Time Complexity: O(n), where n is the number of elements in the array because we loop through each element once.
Space Complexity: O(1), as we use only a fixed amount of additional space.
public class ArrayReducer {
    public static int Reduce(int[] nums, Func<int, int, int> fn, int init) {
        int result = init;
        foreach (var num in nums) {
            result = fn(result, num);
        }
        return result;
    }
    public static int Sum(int accum, int curr) {
        return accum + curr;
    }
    public static void Main() {
        int[] nums = {1, 2, 3, 4};
        int init = 0;
        int result = Reduce(nums, Sum, init);
        Console.WriteLine(result);
    }
}This C# program defines the method Reduce which leverages the Func delegate to apply the reduction function over the array. The reduction function Sum simply sums two integers.
This approach employs a recursive strategy to apply the reducer function on each element of the array. By defining a base case for the recursion (i.e., an empty array returns the initial value), the recursion continues until all elements are processed. Care must be taken with recursion due to stack size limitations for large inputs.
Time Complexity: O(n), for traversing each element.
Space Complexity: O(n), due to recursion stack consumption.
1def reduce_recursive(nums, fn, init, index=0):
2    if index == len(nums):
3        return init
4    return fn(reduce_recursive(nums, fn, init, index + 1), nums[index])
5
6def sum_fn(accum, curr):
7    return accum + curr
8
9nums = [1, 2, 3, 4]
10init = 0
11result = reduce_recursive(nums, sum_fn, init)
12print(result)The Python version of recursive reduction calls itself incrementing the index. It terminates once all elements are processed, returning the accumulated value for an empty slice as the base result.