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

Apply Transform Over Each Element in Array

Difficulty: Easy


Problem Description

Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element. The returned array should be created such that returnedArray[i] = fn(arr[i], i).


Key Insights

  • Each element in the input array needs to be transformed using the provided function.
  • The transformation function can utilize both the element and its index.
  • The output should maintain the order of the input array.
  • We need to implement the solution without using built-in array methods such as Array.map.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the input array. Space Complexity: O(n), for storing the new transformed array.


Solution

To solve the problem, we will create a new array to store the transformed elements. We'll iterate over each element in the input array, apply the transformation function fn to each element along with its index, and populate the new array with the results. This approach ensures that we maintain the order of elements and apply the transformation correctly.


Code Solutions

def transform(arr, fn):
    # Create a new list to store transformed elements
    transformed_array = []
    # Iterate over each element in the input array
    for i in range(len(arr)):
        # Apply the transformation function and append to the new array
        transformed_array.append(fn(arr[i], i))
    return transformed_array
← Back to All Questions