Apply Transform Over Each Element in Array - Problem
Given an integer array arr and a transformation function fn, return a new array with the transformation applied to each element.
The returned array should be created such that returnedArray[i] = fn(arr[i], i), where the function receives both the element value and its index as parameters.
Important: You must implement this without using the built-in Array.map() method.
Example: If arr = [1, 2, 3] and fn = (x, i) => x + i, then the result should be [1+0, 2+1, 3+2] = [1, 3, 5].
Input & Output
example_1.js โ Basic Addition
$
Input:
arr = [1, 2, 3], fn = (x, i) => x + i
โบ
Output:
[1, 3, 5]
๐ก Note:
For each element, we add its value to its index: arr[0]=1+0=1, arr[1]=2+1=3, arr[2]=3+2=5
example_2.js โ Multiplication
$
Input:
arr = [10, 20, 30], fn = (x, i) => x * 2
โบ
Output:
[20, 40, 60]
๐ก Note:
Each element is doubled (index is ignored in this function): 10*2=20, 20*2=40, 30*2=60
example_3.js โ Edge Case
$
Input:
arr = [5], fn = (x, i) => x * i
โบ
Output:
[0]
๐ก Note:
Single element at index 0: 5 * 0 = 0. This demonstrates how index can significantly affect the result
Constraints
- 0 โค arr.length โค 1000
- -109 โค arr[i] โค 109
- fn returns an integer
- The transformation function fn is always provided and valid
Visualization
Tap to expand
Understanding the Visualization
1
Input Conveyor
Products arrive on the input belt, each with a position number
2
Transformation Station
Worker applies fn(product, position) to transform each item
3
Output Collection
Transformed products are placed on the output belt in order
4
Final Result
Complete transformed array is ready for delivery
Key Takeaway
๐ฏ Key Insight: Array transformation is a linear operation that requires exactly one pass through the input data, making it inherently O(n) in both time and space complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code