Difficulty: Easy | Acceptance: 86.20% | Paid: No Topics: Array, Function
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 transformedArray[i] = fn(arr[i], i).
Please solve it without using the built-in Array.map method.
- Examples
- Constraints
- Approach 1: Iterative Loop
- Approach 2: Built-in Map
Examples
Example 1:
Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
Output: [2,3,4]
Explanation:
const newArray = arr.map(fn) // [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 is at in the array.
Example 3:
Input: arr = [10,20,30], fn = function constant() { return 42; }
Output: [42,42,42]
Explanation: The function always returns 42 regardless of the input.
Constraints
0 <= arr.length <= 1000
-10^9 <= arr[i] <= 10^9
fn returns a number
Approach 1: Iterative Loop
Intuition Create a new array of the same length as the input. Iterate through the input array, apply the transformation function to each element and its index, and store the result in the new array.
Steps
- Initialize an empty array
resto store the results. - Iterate through the input array
arrusing a loop from index0toarr.length - 1. - In each iteration, call the function
fnpassing the current elementarr[i]and the indexi. - Push the result of
fninto theresarray. - Return the
resarray.
python
from typing import List, Callable
class Solution:
def map(self, arr: List[int], fn: Callable[[int, int], int]) -> List[int]:
res = []
for i in range(len(arr)):
res.append(fn(arr[i], i))
return resComplexity
- Time: O(n) - We iterate through the array once.
- Space: O(n) - We create a new array to store the results.
- Notes: This is the most fundamental approach and works in all languages.
Approach 2: Built-in Map
Intuition
Use the languageās native functional programming feature (like map, list comprehension, or streams) to transform the array in a declarative way.
Steps
- Call the built-in map function on the array, passing the provided function
fn. - Return the resulting array.
python
from typing import List, Callable
class Solution:
def map(self, arr: List[int], fn: Callable[[int, int], int]) -> List[int]:
return [fn(x, i) for i, x in enumerate(arr)]Complexity
- Time: O(n) - The built-in map iterates through the array once.
- Space: O(n) - A new array is created to store the results.
- Notes: This approach is more concise and idiomatic in high-level languages, though the problem statement specifically asks to solve it without the built-in method.