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] <= 109This 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.
C++
Java
Python
C#
JavaScript
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.
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.
| 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. |
Product of Array Except Self - Leetcode 238 - Python • NeetCode • 747,485 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