Talentd
FleetCode
Make and follow sheets.Sign in

Apply Transform Over Each Element in Array solution and explanation

Easy5 min read86.0% acceptanceUpdated 9 Apr 2026
Apply Transform over each Element in Array (Transform) - Leetcode 2635 - JavaScript 30-Day ChallengeNeetCodeIO · 6:58 · 24K viewsWatch on YouTube
9 more videos on this problem
  1. Apply Transform over each Element in Array (Transform) - Leetcode 2635 - JavaScript 30-Day ChallengeNeetCodeIO · 6:58 · 24K views
  2. Apply Transform Over Each Element in Array | Leetcode 2635 | 30 Days of JavaScript #leetcodeLearn With Chirag · 15:45 · 4K views
  3. 2635. Apply Transform Over Each Element in Array - Leetcode JavaScript Solution with ExplanationEndeavour Monk · 10:38 · 2K views
  4. #day5 | 2635. Apply Transform Over Each Element in Array | 30 Days of Javascript | Leetcode-2635Coding with Ankita · 11:30 · 1K views
  5. 2635. Apply Transform Over Each Element in Array - Day 4/30 Leetcode Javascript ChallengeProgramming Live with Larry · 3:56 · 445 views
  6. Leetcode Day 4 JavaScript Challenge Solution: 2635. Apply Transform Over Each Element in ArrayvanAmsen · 3:27 · 258 views
  7. Apply Transform Over Each Element in Array - LeetCode 2635 - JavaScript - JS 30 Day Challenge Day 4Alpha-Code · 10:11 · 174 views
  8. LeetCode 30 Days of JavaScript: Apply Transform Over Each Element in Array | Programming TutorialCodeByAbi · 4:51 · 154 views
  9. Apply Transform Over Each Element in Array - Leetcode 2635 | Ultimate JavaScript SheetConnectVerse · 9:12 · 149 views
  10. Apply Transform Over Each Element in Array in Javascript - 30-Day Leetcode Challenge #5PJ Web Dev · 3:47 · 104 views

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

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.

Approach overview

Problem Overview: You receive an array arr and a transformation function fn. The task is to apply fn to every element in the array and return a new array containing the transformed results. The function typically receives the element and its index, similar to the behavior of map() in many programming languages.

Approach 1: Using a For Loop (Time: O(n), Space: O(n))

The most direct solution iterates through the array once and applies the transformation function to each element. For each index i, compute fn(arr[i], i) and append the result to a new output array. This approach uses simple iteration and avoids additional overhead from function calls or recursion. Since each element is processed exactly once, the time complexity is O(n). The output array stores n transformed elements, giving a space complexity of O(n). This approach works well in any language and mirrors how a built‑in map implementation works internally.

From a data structures perspective, the problem operates purely on an array. The algorithm performs sequential access, which is cache-friendly and efficient. If you were implementing functional utilities or building a lightweight version of map, this loop-based strategy is the most practical and readable.

Approach 2: Using Recursion (Time: O(n), Space: O(n))

A recursive solution processes the array element by element through function calls. The base case stops when the index reaches the array length. Otherwise, compute the transformed value for the current index and combine it with the recursive result of the remaining elements. Conceptually, the recursion simulates iteration: each call handles one element and delegates the rest of the work to the next call.

The time complexity remains O(n) because each element is still processed once. However, recursion adds call stack overhead, resulting in an additional O(n) stack space in the worst case. This makes it slightly less efficient than the iterative approach for large arrays. Still, recursion is useful when practicing recursion patterns or demonstrating functional-style transformations common in functional programming.

Recommended for interviews: The iterative for loop approach is what interviewers usually expect. It clearly shows you understand array traversal and function application while keeping both time and space complexity optimal at O(n). Mentioning recursion can demonstrate conceptual depth, but the loop version is typically preferred because it avoids unnecessary stack usage and keeps the implementation straightforward.

Approach 1: Using a For Loop

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.

def transform_array(arr, fn):
    return [fn(arr[i], i) for i in range(len(arr))]

# Example usage
arr = [1, 2, 3]
def plus_one(n, i):
    return n + 1

result = transform_array(arr, plus_one)
print(result)
import java.util.ArrayList;
import java.util.List;

public class TransformArray {
    public static List<Integer> transformArray(int[] arr, ArrFunction fn) {
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            result.add(fn.apply(arr[i], i));
        }
        return result;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        List<Integer> result = transformArray(arr, (n, i) -> n + 1);
        System.out.println(result);
    }
}

@FunctionalInterface
interface ArrFunction {
    int apply(int n, int i);
}
#include <iostream>
#include <vector>

std::vector<int> transformArray(const std::vector<int>& arr, int(*fn)(int, int)) {
    std::vector<int> result;
    for (size_t i = 0; i < arr.size(); ++i) {
        result.push_back(fn(arr[i], static_cast<int>(i)));
    }
    return result;
}

int plusOne(int n, int i) {
    return n + 1;
}

int main() {
    std::vector<int> arr = {1, 2, 3};
    std::vector<int> result = transformArray(arr, plusOne);
    for (int val : result) {
        std::cout << val << ' ';
    }
    return 0;
}
function transformArray(arr, fn) {
    const result = [];
    for (let i = 0; i < arr.length; i++) {
        result.push(fn(arr[i], i));
    }
    return result;
}

const arr = [1, 2, 3];
const plusOne = (n, i) => n + 1;

console.log(transformArray(arr, plusOne));
#include <stdio.h>

int* transformArray(int* arr, int arrSize, int(*fn)(int, int)) {
    int* result = (int*)malloc(arrSize * sizeof(int));
    for(int i = 0; i < arrSize; i++) {
        result[i] = fn(arr[i], i);
    }
    return result;
}

int plusOne(int n, int i) {
    return n + 1;
}

int main() {
    int arr[] = {1, 2, 3};
    int arrSize = sizeof(arr) / sizeof(arr[0]);
    int* result = transformArray(arr, arrSize, plusOne);
    for(int i = 0; i < arrSize; i++) {
        printf("%d ", result[i]);
    }
    free(result);
    return 0;
}
using System;
using System.Collections.Generic;

public class Program
{
    public static List<int> TransformArray(int[] arr, Func<int, int, int> fn)
    {
        List<int> result = new List<int>();
        for (int i = 0; i < arr.Length; i++)
        {
            result.Add(fn(arr[i], i));
        }
        return result;
    }

    public static void Main()
    {
        int[] arr = { 1, 2, 3 };
        List<int> result = TransformArray(arr, (n, i) => n + 1);
        Console.WriteLine(String.Join(", ", result));
    }
}

The Python solution uses a list comprehension to iterate over the array, applying the function to each element in a concise manner.

Complexity

Time Complexity: O(n)
Space Complexity: O(n)

Try this approach in the editor

Approach 2: Using Recursion

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.

def transform_array_recursive(arr, fn, index=0, result=None):
    if result is None:
        result = []
    if index == len(arr):
        return result
    result.append(fn(arr[index], index))
    return transform_array_recursive(arr, fn, index + 1, result)

# Example usage
arr = [1, 2, 3]
plus_one = lambda n, i: n + 1
result = transform_array_recursive(arr, plus_one)
print(result)
import java.util.ArrayList;
import java.util.List;

public class TransformArrayRecursive {
    public static void transformArrayRecursive(int[] arr, List<Integer> result, int index, ArrFunction fn) {
        if (index >= arr.length) return;
        result.add(fn.apply(arr[index], index));
        transformArrayRecursive(arr, result, index + 1, fn);
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        List<Integer> result = new ArrayList<>();
        transformArrayRecursive(arr, result, 0, (n, i) -> n + 1);
        System.out.println(result);
    }
}

@FunctionalInterface
interface ArrFunction {
    int apply(int n, int i);
}
#include <iostream>
#include <vector>

void transformArrayRecursive(const std::vector<int>& arr, std::vector<int>& result, int index, int (*fn)(int, int)) {
    if (index >= arr.size()) return;
    result.push_back(fn(arr[index], index));
    transformArrayRecursive(arr, result, index + 1, fn);
}

int plusOne(int n, int i) {
    return n + 1;
}

int main() {
    std::vector<int> arr = {1, 2, 3};
    std::vector<int> result;
    transformArrayRecursive(arr, result, 0, plusOne);
    for (const auto& val : result) {
        std::cout << val << " ";
    }
    return 0;
}
function transformArrayRecursive(arr, fn, index = 0, result = []) {
    if (index === arr.length) return result;
    result.push(fn(arr[index], index));
    return transformArrayRecursive(arr, fn, index + 1, result);
}

const arr = [1, 2, 3];
const plusOne = (n, i) => n + 1;
console.log(transformArrayRecursive(arr, plusOne));
#include <stdio.h>
#include <stdlib.h>

void transformArrayRecursive(int* arr, int* result, int index, int size, int (*fn)(int, int)) {
    if (index >= size) return;
    result[index] = fn(arr[index], index);
    transformArrayRecursive(arr, result, index + 1, size, fn);
}

int plusOne(int n, int i) {
    return n + 1;
}

int main() {
    int arr[] = {1, 2, 3};
    int arrSize = sizeof(arr) / sizeof(arr[0]);
    int* result = (int*)malloc(arrSize * sizeof(int));
    transformArrayRecursive(arr, result, 0, arrSize, plusOne);
    for(int i = 0; i < arrSize; i++) {
        printf("%d ", result[i]);
    }
    free(result);
    return 0;
}
using System;
using System.Collections.Generic;

public class Program
{
    public static void TransformArrayRecursive(int[] arr, List<int> result, int index, Func<int, int, int> fn)
    {
        if (index >= arr.Length) return;
        result.Add(fn(arr[index], index));
        TransformArrayRecursive(arr, result, index + 1, fn);
    }

    public static void Main()
    {
        int[] arr = { 1, 2, 3 };
        List<int> result = new List<int>();
        TransformArrayRecursive(arr, result, 0, (n, i) => n + 1);
        Console.WriteLine(String.Join(", ", result));
    }
}

The Python recursive method transform_array_recursive uses default parameters to iterate and transform the input array recursively.

Complexity

Time Complexity: O(n)
Space Complexity: O(n) due to recursion depth.

Try this approach in the editor

Approach 3: traversal

We traverse the array arr, for each element arr[i], replace it with fn(arr[i], i). Finally, return the array arr.

The time complexity is O(n), where n is the length of the array arr. The space complexity is O(1).

function map(arr: number[], fn: (n: number, i: number) => number): number[] {
    for (let i = 0; i < arr.length; ++i) {
        arr[i] = fn(arr[i], i);
    }
    return arr;
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Using a For Loop

Time Complexity: O(n)
Space Complexity: O(n)

Using Recursion

Time Complexity: O(n)
Space Complexity: O(n) due to recursion depth.

traversal–

Complexity analysis

ApproachTimeSpaceWhen to Use
For Loop IterationO(n)O(n)Best general solution. Efficient traversal and minimal overhead.
RecursionO(n)O(n)Useful for practicing recursive thinking or functional-style transformations.

Frequently asked questions

Is Apply Transform Over Each Element in Array easy or hard?

The problem is classified as Easy. It focuses on basic array traversal and function application. The main goal is understanding how to apply a transformation to each element while building a new result array.

Apply Transform Over Each Element in Array Python/Java solution

In Python or Java, the solution iterates through the array and applies a function to each element while storing results in a new array or list. The logic mirrors the behavior of built‑in map utilities but is implemented manually using a loop or recursion. Both versions run in O(n) time.

How to solve Apply Transform Over Each Element in Array in O(n)?

Traverse the array sequentially and apply the transformation function to each element. Store the computed value in a new result array. Since the algorithm performs one operation per element, it runs in linear time O(n) with O(n) space for the transformed array.

What is the best approach for Apply Transform Over Each Element in Array?

The most efficient approach is iterating through the array with a simple for loop and applying the transformation function to each element. For every index i, compute fn(arr[i], i) and store the result in a new array. This processes each element exactly once, resulting in O(n) time complexity and O(n) space for the output array.

Is Apply Transform Over Each Element in Array asked at Google/Amazon/Meta?

This specific problem is more of a foundational coding exercise rather than a common direct interview question at major companies. However, the concept behind it—array traversal and functional transformations similar to map—is frequently used in coding interviews and real production code.

What data structure is used in Apply Transform Over Each Element in Array?

The primary data structure used is an array. The algorithm iterates through the input array and produces another array containing the transformed values. No advanced structures such as hash maps or trees are required.

What is the time complexity of Apply Transform Over Each Element in Array?

The time complexity is O(n) because each element of the array is visited exactly once. Whether you use a loop or recursion, the transformation function is applied n times. No nested iteration or additional processing is required.

Comments

Now write it yourselfClose this page and solve Apply Transform Over Each Element in Array in the editor, without looking.
Practise Apply Transform Over Each Element in Array