Difficulty: Easy | Acceptance: 85.50% | Paid: No Topics: N/A
Given an integer array arr and a filtering function fn, return a filtered array filteredArr.
The fn function takes an element and an index and returns a boolean. The filtered array should only contain elements where fn returned true.
- Examples
- Constraints
- Iterative Approach
- Built-in Methods
Examples
Example 1
Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
Output: [20,30]
Explanation:
const newArray = filter(arr, greaterThan10);
The function filters out values that are less than or equal to 10.
Example 2
Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
Output: [1]
Explanation:
fn takes the index of the element as an argument.
Since the index of 1 is 0, it passes the check.
Example 3
Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1; }
Output: [-2,0,1,2]
Explanation:
Falsy values like 0 are filtered out.
Constraints
0 <= arr.length <= 1000
-10⁹ <= arr[i] <= 10⁹
fn returns a boolean
Iterative Approach
Intuition The most straightforward way to solve this problem is to iterate through the input array, evaluate the filtering function for each element, and collect the elements that satisfy the condition into a new result array.
Steps
- Initialize an empty array (or list) to store the filtered elements.
- Iterate through the input array using a standard loop, keeping track of the index.
- For each element, call the provided function
fnwith the element and its index. - If
fnreturns a truthy value, append the current element to the result array. - Return the result array after the loop completes.
python
from typing import List, Callable
class Solution:
def filter(self, arr: List[int], fn: Callable[[int, int], bool]) -> List[int]:
filtered_arr = []
for i in range(len(arr)):
if fn(arr[i], i):
filtered_arr.append(arr[i])
return filtered_arrComplexity
- Time: O(n) - We iterate through the array once.
- Space: O(n) - In the worst case, we store all elements in the new array.
- Notes: This is the most compatible approach across different programming paradigms.
Built-in Methods
Intuition
Most modern programming languages provide built-in methods for functional array operations like filter. Using these methods leads to more concise and declarative code.
Steps
- Call the native
filtermethod (or equivalent stream operation) on the input array. - Pass the provided function
fnas the predicate. - Return the resulting array directly.
python
from typing import List, Callable
class Solution:
def filter(self, arr: List[int], fn: Callable[[int, int], bool]) -> List[int]:
return [x for i, x in enumerate(arr) if fn(x, i)]Complexity
- Time: O(n) - The built-in methods iterate through the array internally.
- Space: O(n) - A new array is created to store the results.
- Notes: While concise, built-in methods may have slight overhead compared to a manual loop, but they improve readability.