Given an integer array arr and a filtering function fn, return a filtered array filteredArr.
The fn function takes one or two arguments:
arr[i] - number from the arri - index of arr[i]filteredArr should only contain the elements from the arr for which the expression fn(arr[i], i) evaluates to a truthy value. A truthy value is a value where Boolean(value) returns true.
Please solve it without the built-in Array.filter method.
Example 1:
Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
Output: [20,30]
Explanation:
const newArray = filter(arr, fn); // [20, 30]
The function filters out values that are not greater than 10
Example 2:
Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
Output: [1]
Explanation:
fn can also accept the index of each element
In this case, the function removes elements not at index 0
Example 3:
Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }
Output: [-2,0,1,2]
Explanation:
Falsey values such as 0 should be filtered out
Constraints:
0 <= arr.length <= 1000-109 <= arr[i] <= 109Problem Overview: You receive an array and a function fn. The task is to return a new array containing only the elements for which fn(element, index) evaluates to true. Elements that fail the condition are skipped while preserving the original order.
Approach 1: Iterative Filtering (O(n) time, O(n) space)
The straightforward solution is to iterate through the array once and evaluate the provided function for every element. For each index i, call fn(arr[i], i). If the function returns true, append the element to a result array. Otherwise skip it and continue scanning. This approach uses basic array traversal and conditional checks, making it easy to implement in any language including C, C++, Java, Python, C#, and JavaScript.
The key insight is that filtering does not require modifying the original array. You simply construct a new array while scanning once from left to right. Each element is processed exactly once, giving O(n) time complexity where n is the array length. The result array may contain up to n elements, so the extra space required is O(n).
This approach is typically preferred in imperative languages or when you want maximum clarity during interviews. Every operation is explicit: iterate, evaluate the predicate, and push valid values into the output.
Approach 2: Using Reduce for Filtering (O(n) time, O(n) space)
A functional programming alternative uses the reduce pattern. Instead of manually managing a loop, you accumulate results through a reducer function. During each iteration, the reducer receives the current accumulator (the filtered array) and the current element. If fn(element, index) returns true, push the element into the accumulator before returning it.
This method is common in JavaScript and Python functional-style code. The array is still traversed once, so the time complexity remains O(n). Since the filtered elements are stored in a new accumulator array, the space complexity is also O(n). The difference is mainly stylistic: the logic is expressed through a functional abstraction rather than a manual loop.
Developers who work with functional programming patterns prefer this approach because it composes well with operations like map and filter. It can also make pipelines of transformations easier to read.
Recommended for interviews: Interviewers generally expect the simple iterative approach. It demonstrates clear reasoning about array traversal and conditional filtering with optimal O(n) time. Showing the reduce-based solution afterward signals familiarity with functional patterns, but the loop-based implementation is the safest and most universally readable answer.
This approach involves iterating over each element in the array and using the filtering function to determine which elements should be included in the result. We use a simple loop structure to achieve this.
This C code defines a general 'filter' function that takes an integer array, its size, a function pointer for the filtering criteria, and a pointer to the return size. It iterates through the array and adds elements that satisfy the condition to the result array. A specific example using a 'greaterThan10' function demonstrates the filtering process.
Time Complexity: O(n) where n is the number of elements in the array.
Space Complexity: O(n) for storing the filtered elements.
This approach uses the idea of reduction to accumulate only those elements of the array that satisfy the filtering function's condition. It's an alternative to a straightforward iteration but essentially accomplishes the same filtering.
This JavaScript solution uses the reduce method to build a new array. It accumulates only those elements for which the filtering function returns true. The premise is to use reduction for traversal and condition checking simultaneously.
JavaScript
Python
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(n), as we need additional space to store the filtered elements.
We traverse the array arr and for each element arr[i], if fn(arr[i], i) is true, we add it to the answer array. Finally, we return the answer array.
The time complexity is O(n), where n is the length of the array arr. Ignoring the space consumption of the answer, the space complexity is O(1).
TypeScript
| Approach | Complexity |
|---|---|
| Iterative Filtering | Time Complexity: O(n) where n is the number of elements in the array. |
| Using Reduce for Filtering | Time Complexity: O(n), where n is the number of elements in the array. |
| Traversal | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Iterative Filtering | O(n) | O(n) | Best general solution. Clear logic and works across all languages. |
| Reduce-based Filtering | O(n) | O(n) | Useful when writing functional-style code or chaining transformations. |
Filter Elements from Array (Transforms) - Leetcode 2634 - JavaScript 30-Day Challenge • NeetCodeIO • 16,822 views views
Watch 9 more video solutions →Practice Filter Elements from Array with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor