Filter Elements from Array — LeetCode 2634 Python Solution

EasyJavaScript
Problem
#2634
Reading time
2 min

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

Example

Input
arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
Output
[20,30]
Explanation
const newArray = filter(arr, fn); // [20, 30]

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array arr
SpaceO(1) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2634. Filter Elements from Array?
LeetCode 2634. Filter Elements from Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 2634. Filter Elements from Array?
The Python solution on this page runs in O(n), where n is the length of the array arr.
What is the space complexity of LeetCode 2634. Filter Elements from Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2634. Filter Elements from Array cover?
LeetCode 2634. Filter Elements from Array is tagged JavaScript on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview