Apply Transform Over Each Element in Array - Problem
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.
Input & Output
Example 1 — Add One to Each Element
$
Input:
arr = [1,2,3], fn = function plusone(n) { return n + 1; }
›
Output:
[2,3,4]
💡 Note:
Apply fn to each element: fn(1,0)=2, fn(2,1)=3, fn(3,2)=4
Example 2 — Add Index to Element
$
Input:
arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
›
Output:
[1,3,5]
💡 Note:
Add index to each element: fn(1,0)=1+0=1, fn(2,1)=2+1=3, fn(3,2)=3+2=5
Example 3 — Constant Function
$
Input:
arr = [10,20,30], fn = function constant() { return 42; }
›
Output:
[42,42,42]
💡 Note:
Function returns constant: fn(10,0)=42, fn(20,1)=42, fn(30,2)=42
Constraints
- 0 ≤ arr.length ≤ 1000
- -109 ≤ arr[i] ≤ 109
- fn returns an integer
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,2,3] and function fn(x,i) = x + i + 1
2
Process
Apply function to each element with its index
3
Output
Transformed array [2,4,6]
Key Takeaway
🎯 Key Insight: Transform each element using both its value and index position
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code