Taro Logo

Apply Transform Over Each Element in Array

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+3
More companies
Profile picture
Profile picture
Profile picture
51 views
Topics:
Arrays

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).

Please solve it without the built-in Array.map method.

Example 1:

Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
Output: [2,3,4]
Explanation:
const newArray = map(arr, plusone); // [2,3,4]
The function increases each value in the array by one. 

Example 2:

Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
Output: [1,3,5]
Explanation: The function increases each value by the index it resides in.

Example 3:

Input: arr = [10,20,30], fn = function constant() { return 42; }
Output: [42,42,42]
Explanation: The function always returns 42.

Constraints:

  • 0 <= arr.length <= 1000
  • -109 <= arr[i] <= 109
  • fn returns an integer.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the values within the `nums` array (e.g., range, data type, presence of negative numbers, nulls, or NaN)?
  2. Can the input array `nums` be empty or null? If so, what should the function return?
  3. Is the function `fn` guaranteed to be a pure function (i.e., no side effects) and always return a value?
  4. Is there a specific data type expected for the return values of the function `fn`? Does it need to match the data type in the original array?
  5. Are there any memory constraints or limitations on the size of the new array that is returned?

Brute Force Solution

Approach

The goal is to create a new collection of numbers where each number is transformed based on a specific rule. The brute force approach involves going through each number in the original collection one by one and applying the transformation to it.

Here's how the algorithm would work step-by-step:

  1. Take the first number from the original collection.
  2. Apply the given transformation rule to this number. For example, if the rule is to double each number, then double the first number.
  3. Place the transformed number into a new collection.
  4. Repeat the process for the second number in the original collection.
  5. Continue this process for every number in the original collection.
  6. The new collection will now contain all the transformed numbers in the same order as the original collection.

Code Implementation

def apply_transform(original_array, transform_function):
    transformed_array = []

    # Iterate through each element of the original array
    for array_index in range(len(original_array)): 

        # Get the current element from the array
        current_element = original_array[array_index]

        # Apply the transformation function to the element
        transformed_element = transform_function(current_element)

        # Append the transformed element to the new array
        transformed_array.append(transformed_element)

    # Return the new array with transformed elements
    return transformed_array

Big(O) Analysis

Time Complexity
O(n)The algorithm iterates through each element in the input array of size n exactly once. For each element, a transformation function is applied, which is assumed to take constant time. Therefore, the overall time complexity is directly proportional to the number of elements in the array, resulting in O(n).
Space Complexity
O(N)The brute force approach, as described, creates a new collection to store the transformed numbers. The size of this new collection is equal to the number of elements in the original collection. Therefore, we need an auxiliary array of size N, where N is the number of elements in the input array. Thus, the space complexity is O(N).

Optimal Solution

Approach

The best way to solve this is to go through each element in the input one by one. For each element, we apply a given rule and save the result. At the end, we simply return the result.

Here's how the algorithm would work step-by-step:

  1. Start with an empty container to hold the transformed numbers.
  2. Take the first number from the original input.
  3. Apply the given instruction (the function) to this number.
  4. Put the result of this instruction into the container we prepared earlier.
  5. Move to the next number in the original input and repeat steps 3 and 4.
  6. Keep doing this until you've processed every number in the original input.
  7. Return the container with all the transformed numbers.

Code Implementation

def apply_transform_over_each_element_in_array(input_array, transform_function):
    transformed_array = []

    # Iterate through each element of the input array
    for element in input_array:

        # Apply the transformation function to the current element
        transformed_element = transform_function(element)

        # Add the transformed element to the result array
        transformed_array.append(transformed_element)

    # Return the array containing the transformed elements
    return transformed_array

Big(O) Analysis

Time Complexity
O(n)The algorithm iterates through each element of the input array once. For each element, it applies a transformation function. Applying the function is assumed to take constant time, O(1). Since we perform this constant-time operation for each of the n elements in the array, the overall time complexity is O(n).
Space Complexity
O(N)The algorithm creates a new container to store the transformed numbers. In the worst case, the transformed container will hold one transformed value for each element in the original input array. Therefore, the auxiliary space used is directly proportional to the number of elements in the input array, denoted as N. This means the space complexity is O(N).

Edge Cases

Null or undefined input array nums
How to Handle:
Return an empty array or throw an error based on the problem's specific requirements.
Empty input array nums
How to Handle:
Return an empty array as there are no elements to transform.
Null or undefined function fn
How to Handle:
Throw an error since the transformation cannot be applied without a valid function.
fn throws an error during execution
How to Handle:
Catch the exception thrown by fn and handle it appropriately, either by logging the error or re-throwing it.
Large input array nums (close to memory limits)
How to Handle:
Ensure that the new array creation doesn't cause memory overflow; consider in-place transformation if feasible.
Function fn returns non-numeric values
How to Handle:
Type-check the returned value of fn and handle it based on the expected output type of the transformed array.
Function fn has side effects
How to Handle:
Document this behavior or discourage it as side effects can make debugging and reasoning about the code harder.
nums contains very large numbers
How to Handle:
Consider potential for integer overflow in the transformed array if fn involves arithmetic operations.