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

Number: 2761

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given an integer array, a reducer function, and an initial value, compute a final result by iteratively applying the reducer. Start by applying the function to the initial value and the first element, then use the result with the next element, and so on. If the array is empty, simply return the initial value.


Key Insights

  • Iterate through the array sequentially.
  • Maintain an accumulator that stores the result of the previous computation.
  • Update the accumulator by applying the reducer function on it and the current element.
  • Special case: return the initial value if the array is empty.

Space and Time Complexity

Time Complexity: O(n) - We process each element once. Space Complexity: O(1) - Only a constant amount of extra space is used.


Solution

The solution uses a simple linear iteration over the elements of the array. An accumulator is initialized with the initial value, and for each element, the accumulator is updated by applying the reducer function. This approach ensures that each element is processed in order, leading to the final result without using additional data structures. The in-place update of the accumulator helps in achieving constant space complexity while ensuring a single pass over the array for linear time complexity.


Code Solutions

def reduce_transformation(nums, fn, init):
    # Initialize the accumulator with the initial value.
    accumulator = init
    # Iterate over each element in the numbers list.
    for number in nums:
        # Update the accumulator by applying the reducer function.
        accumulator = fn(accumulator, number)
    # Return the final accumulated value.
    return accumulator

# Example usage:
if __name__ == "__main__":
    # Define a reducer function to sum the values.
    def sum_fn(accum, curr):
        return accum + curr
    
    # Test with example input; expected output is 10.
    print(reduce_transformation([1, 2, 3, 4], sum_fn, 0))
← Back to All Questions