
Sponsored
Sponsored
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.
Time Complexity: O(n) where n is the number of elements in the array.
Space Complexity: O(n) for storing the filtered elements.
1
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.
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.
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.
1function filterUsingReduce(arr, fn) {
2 return arr.reduce((acc, item, index) => {
3 if (fn(item, index)) {
4 acc.push(item);
5 }
6 return acc;
7 }, []);
8}
9
10function greaterThan10(n, i) {
11 return n > 10;
12}
13
14const arr = [0, 10, 20, 30];
15const filteredArr = filterUsingReduce(arr, greaterThan10);
16console.log(filteredArr);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.