Skip to main content

Filter Elements from Array - Solution & Explanation

Easy9 min readAsked at: Amazon, Google, Bloomberg
Practice this problem

Problem Statement

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 arr
  • i - 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] <= 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.

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.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) where n is the number of elements in the array.
Space Complexity: O(n) for storing the filtered elements.

Try this approach in the editor →

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.

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.

Code

JavaScript

Python

Complexity

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.

Try this approach in the editor →

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

Code

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Iterative Filtering

Time Complexity: O(n) where n is the number of elements in the array.
Space Complexity: O(n) for storing the filtered elements.

Using Reduce for Filtering

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.

Traversal—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Iterative FilteringO(n)O(n)Best general solution. Clear logic and works across all languages.
Reduce-based FilteringO(n)O(n)Useful when writing functional-style code or chaining transformations.

Video Solution

Filter Elements from Array (Transforms) - Leetcode 2634 - JavaScript 30-Day Challenge • NeetCodeIO • 17,112 views views

Watch 9 more video solutions →

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.

Ready to solve this problem?

Practice Filter Elements from Array with our built-in code editor and test cases.

Practice on FleetCode