We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Array Reduce Transformation

Difficulty: Easy


Problem Description

Given an integer array nums, a reducer function fn, and an initial value init, return the final result obtained by executing the fn function on each element of the array, sequentially, passing in the return value from the calculation on the preceding element. If the length of the array is 0, the function should return init.


Key Insights

  • The problem requires applying a reducer function iteratively over an array.
  • The reducer function takes two parameters: an accumulator and the current array element.
  • The output of the reducer function for each element becomes the input for the next element.
  • If the array is empty, the initial value should be returned directly.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the input array nums. Space Complexity: O(1), as we are using a constant amount of space for the accumulator.


Solution

To solve this problem, we will use a simple iterative approach. We'll initialize a variable to hold the accumulator with the value of init. We will then loop through each element in the nums array, applying the reducer function fn to the accumulator and the current element. This process continues until all elements have been processed, and we finally return the accumulator.

The data structure used is a simple variable to store the accumulator, and the algorithm follows a linear traversal approach through the array.


Code Solutions

def array_reduce(nums, fn, init):
    val = init
    for num in nums:
        val = fn(val, num)
    return val
← Back to All Questions