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] <= 109fn returns an integer.This approach involves manually iterating over each element of the array using a for loop. For each element, we apply the provided function fn with the current element and its index as arguments. The result is then pushed into a new result array, which is returned at the end.
The C solution defines a function transformArray that takes an array, its size, and a function pointer. It allocates memory for a new result array, iterates over the input array, and applies the function fn, storing results in result. Finally, it returns the result array.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(n) for the resultant array.
Another approach is to use recursion to apply the function to each element in the array. We define a recursive function that processes elements by moving from the start to the end of the array, applying transformations and constructing the result array.
In the recursive C solution, a helper function transformArrayRecursive is created. It recursively calls itself to apply the function to each element, building up the result array.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(n) for result array and O(n) for function call stack.
| Approach | Complexity |
|---|---|
| Using a For Loop | Time Complexity: O(n), where n is the number of elements in the array. |
| Using Recursion | Time Complexity: O(n) |
Apply Transform over each Element in Array (Transform) - Leetcode 2635 - JavaScript 30-Day Challenge • NeetCodeIO • 20,647 views views
Watch 9 more video solutions →Practice Apply Transform Over Each Element in Array with our built-in code editor and test cases.
Practice on FleetCode