Filter Elements from Array solution and explanation
9 more videos on this problem
Filter Elements from Array (Transforms) - Leetcode 2634 - JavaScript 30-Day ChallengeNeetCodeIO · 12:35 · 17K views
Filter Elements from Array | Leetcode 2634 | 30 Days of JavaScript #leetcode #javascriptLearn With Chirag · 9:51 · 3K views
2634. Filter Elements from Array - Leetcode JavaScript Solution with ExplanationEndeavour Monk · 6:50 · 1K views
Leetcode javascript Day-5 || 2634 Filter Elements from ArrayAnshulOnTech · 5:06 · 892 views
2634. Filter Elements from Array - Day 5/30 Leetcode Javascript ChallengeProgramming Live with Larry · 1:20 · 298 views
30 days of JavaScript - Filter Elements from ArrayCode With Bertrand · 19:45 · 225 views
2634. Filter Elements from Array 😎 || Leetcode 30 days JavaScript challenge✌Phoenix Code Lover · 1:57 · 219 views
2634 Filter Elements from Array #Dsa #java #students #leetcode #loop #javascript #solutionStart_Coding · 1:07 · 172 views
Master JavaScript: Custom Array Filtering Function | Leetcode Challenge Day 5 - 2634vanAmsen · 3:46 · 129 views
Filter Elements From Array - LeetCode 2634 - JavaScript - JS 30 Day Challenge Day 5Alpha-Code · 15:19 · 113 views
The problem
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 thearri- index ofarr[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] <= 109
Approach overview
Problem 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.
Approach 1: Iterative Filtering
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.
def filter_array(arr, fn):
return [x for i, x in enumerate(arr) if fn(x, i)]
def greater_than_10(n, i):
return n > 10
arr = [0, 10, 20, 30]
filtered_arr = filter_array(arr, greater_than_10)
print(filtered_arr)import java.util.ArrayList;
import java.util.List;
public class FilterExample {
public static List<Integer> filter(int[] arr, FilterFunction fn) {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
if (fn.apply(arr[i], i)) {
result.add(arr[i]);
}
}
return result;
}
public static boolean greaterThan10(int n, int i) {
return n > 10;
}
public interface FilterFunction {
boolean apply(int n, int i);
}
public static void main(String[] args) {
int[] arr = {0, 10, 20, 30};
List<Integer> filteredArr = filter(arr, FilterExample::greaterThan10);
filteredArr.forEach(n -> System.out.print(n + " "));
}
}#include <iostream>
#include <vector>
std::vector<int> filter(const std::vector<int>& arr, bool (*fn)(int, int)) {
std::vector<int> result;
for (int i = 0; i < arr.size(); ++i) {
if (fn(arr[i], i)) {
result.push_back(arr[i]);
}
}
return result;
}
bool greaterThan10(int n, int i) {
return n > 10;
}
int main() {
std::vector<int> arr = {0, 10, 20, 30};
std::vector<int> filteredArr = filter(arr, greaterThan10);
for (int num : filteredArr) {
std::cout << num << " ";
}
return 0;
}function filter(arr, fn) {
const result = [];
for (let i = 0; i < arr.length; i++) {
if (fn(arr[i], i)) {
result.push(arr[i]);
}
}
return result;
}
function greaterThan10(n, i) {
return n > 10;
}
const arr = [0, 10, 20, 30];
const filteredArr = filter(arr, greaterThan10);
console.log(filteredArr);#include <stdio.h>
#include <stdlib.h>
int* filter(int* arr, int arrSize, int (*fn)(int, int), int* returnSize) {
int* result = (int*)malloc(arrSize * sizeof(int));
*returnSize = 0;
for (int i = 0; i < arrSize; i++) {
if (fn(arr[i], i)) {
result[(*returnSize)++] = arr[i];
}
}
return result;
}
int greaterThan10(int n, int i) {
return n > 10;
}
int main() {
int arr[] = {0, 10, 20, 30};
int returnSize;
int* filteredArr = filter(arr, 4, greaterThan10, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d ", filteredArr[i]);
}
free(filteredArr);
return 0;
}using System;
using System.Collections.Generic;
class FilterExample {
public static List<int> Filter(int[] arr, Func<int, int, bool> fn) {
List<int> result = new List<int>();
for (int i = 0; i < arr.Length; i++) {
if (fn(arr[i], i)) {
result.Add(arr[i]);
}
}
return result;
}
public static bool GreaterThan10(int n, int i) {
return n > 10;
}
static void Main() {
int[] arr = {0, 10, 20, 30};
List<int> filteredArr = Filter(arr, GreaterThan10);
Console.WriteLine(string.Join(" ", filteredArr));
}
}The Python code uses list comprehension to filter elements that satisfy the function. It enumerates the list to get both the element and index, applying the function to decide which elements to keep.
Time Complexity: O(n) where n is the number of elements in the array.
Space Complexity: O(n) for storing the filtered list.
Approach 2: Using Reduce for Filtering
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.
from functools import reduce
def filter_using_reduce(arr, fn):
return reduce(lambda acc, val_index: acc + [val_index[1]] if fn(val_index[1], val_index[0]) else acc, enumerate(arr), [])
def greater_than_10(n, i):
return n > 10
arr = [0, 10, 20, 30]
filtered_arr = filter_using_reduce(arr, greater_than_10)
print(filtered_arr)function filterUsingReduce(arr, fn) {
return arr.reduce((acc, item, index) => {
if (fn(item, index)) {
acc.push(item);
}
return acc;
}, []);
}
function greaterThan10(n, i) {
return n > 10;
}
const arr = [0, 10, 20, 30];
const filteredArr = filterUsingReduce(arr, greaterThan10);
console.log(filteredArr);In Python, the reduce function is used to accumulate the filtered results. It checks each element against the filter criterion and adds it to the result list if it meets the conditions.
Time Complexity: O(n), where n is the number of elements.
Space Complexity: O(n), as it forms a new list for the results.
Approach 3: Traversal
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).
function filter(arr: number[], fn: (n: number, i: number) => any): number[] {
const ans: number[] = [];
for (let i = 0; i < arr.length; ++i) {
if (fn(arr[i], i)) {
ans.push(arr[i]);
}
}
return ans;
}Complexity comparison
| 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. |
| Traversal | – |
Complexity analysis
| 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. |
Frequently asked questions
Is Filter Elements from Array easy or hard?
Filter Elements from Array is considered an easy problem. It focuses on basic array traversal, condition evaluation, and building a result array. The main goal is understanding how predicate-based filtering works in linear time.
Filter Elements from Array Python/Java solution
In Python or Java, iterate through the array or list and check each element with the provided condition. If the condition evaluates to true, append the element to a new list or array structure. This maintains O(n) time complexity and is the most direct implementation across languages.
How to solve Filter Elements from Array in O(n)?
Iterate through the array once and apply the provided predicate function to every element. If the function returns true, append that element to a new result array. Since the array is scanned only once and each operation inside the loop is constant time, the overall complexity stays O(n).
What is the best approach for Filter Elements from Array?
The best approach is a single-pass iterative filter. Traverse the array, evaluate the condition function for each element, and append valid elements to a result array. This runs in O(n) time and uses O(n) space for the output array while keeping the logic simple and readable.
Is Filter Elements from Array asked at Google/Amazon/Meta?
Filtering arrays using predicates is a common concept tested in interviews at companies like Google, Amazon, and Meta. While this exact problem may appear in simplified form, the underlying idea of array traversal and condition-based filtering frequently appears in coding interviews.
What data structure is used in Filter Elements from Array?
The problem primarily uses arrays. The solution iterates through the input array and constructs a new array containing elements that satisfy the given predicate function. No advanced data structures are required.
What is the time complexity of Filter Elements from Array?
The time complexity is O(n) because each element in the array is evaluated exactly once against the filtering function. No nested loops or repeated scans are required. The space complexity is O(n) in the worst case if all elements pass the filter and must be stored in the result array.
