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

Number: 2747

Difficulty: Easy

Paid? No

Companies: Google, Amazon, Apple, Microsoft, Adobe


Problem Description

Given an integer array arr and a function fn, return a new array where each element at index i is the result of applying fn to arr[i] and the index i.


Key Insights

  • Iterate through the array using a loop.
  • For each element, apply the provided function with the element and its index as parameters.
  • Append the result to a new array.
  • Avoid using built-in mapping methods (like Array.map).

Space and Time Complexity

Time Complexity: O(n) - where n is the number of elements in the array, since we iterate through all elements once.
Space Complexity: O(n) - as we create a new array to store the transformed elements.


Solution

The solution involves iterating through the input array using a simple loop. For each element at index i, call the function fn with the element and its index. Store the result in a newly created array. Finally, return the new array containing all transformed elements. This approach uses basic looping and conditional execution without relying on higher-order built-in methods, making it straightforward and efficient.


Code Solutions

# Define the function that applies the transformation over each element in the array.
def transform_array(arr, fn):
    # Initialize an empty list to store the transformed results.
    result = []
    # Iterate over the indices of the array.
    for i in range(len(arr)):
        # Apply the transformation function on the current element and its index.
        transformed_value = fn(arr[i], i)
        # Append the transformed value to the result list.
        result.append(transformed_value)
    # Return the list containing all transformed values.
    return result

# Example usage:
if __name__ == "__main__":
    arr = [1, 2, 3]
    # Define a transformation function that adds 1 to each element.
    def plusone(n, i):
        return n + 1
    print(transform_array(arr, plusone))  # Output: [2, 3, 4]
← Back to All Questions