We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Filter Elements from Array

Difficulty: Easy


Problem Description

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


Key Insights

  • The filtering function can take either one or two arguments (the element and its index).
  • A "truthy" value is any value that evaluates to true when passed to the Boolean constructor.
  • The solution must be implemented without using the built-in Array.filter method.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the input array arr, as we must examine each element once.
Space Complexity: O(n), for the space required to store the filtered result.


Solution

To solve the problem, we will iterate through each element of the input array arr using a loop. For each element, we will call the filtering function fn with the current element and its index. If the result of the function call is truthy, we will add that element to a new array. Finally, we will return the new array containing all the elements that passed the filter.

The approach involves:

  1. Initializing an empty array to store the filtered results.
  2. Looping through each element of the input array.
  3. Applying the filtering function to each element and its index.
  4. Checking if the result is truthy, and if so, adding the element to the results array.

Code Solutions

def filter(arr, fn):
    filteredArr = []
    for i in range(len(arr)):
        if fn(arr[i], i):
            filteredArr.append(arr[i])
    return filteredArr
← Back to All Questions