
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.
1
In this C implementation, the reduce function takes an array, its size, a function pointer fn, and an initial value. It iteratively processes each element of the array, updating the result with the output of the given function fn. The helper function sum simply adds 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.
1#include <stdio.h>
2
3int reduce_recursive(int* nums, int numsSize, int (*fn)(int, int), int init) {
4 if (numsSize == 0) return init;
5 return fn(reduce_recursive(nums + 1, numsSize - 1, fn, init), nums[0]);
6}
7
8int sum(int accum, int curr) {
9 return accum + curr;
10}
11
12int main() {
13 int nums[] = {1, 2, 3, 4};
14 int init = 0;
15 int result = reduce_recursive(nums, 4, sum, init);
16 printf("%d\n", result);
17 return 0;
18}The C recursive method reduce_recursive operates by calling itself on the rest of the array, reducing the size each time. The base case returns the initial value when the array is empty. This approach involves plain recursion without stack manipulation.