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

Number: 2746

Difficulty: Easy

Paid? No

Companies: Google, Microsoft


Problem Description

Given an integer array and a filtering function, return a filtered array that contains only the elements for which invoking the function with the element (and its index) returns a truthy value. Do this without using the built-in Array.filter method.


Key Insights

  • Iterate over the provided array.
  • For each element, call the filtering function with the element and its index.
  • Append the element to the result array if the function returns a truthy value.
  • Do not use built-in methods like Array.filter; implement the filtering manually.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(n) in the worst case when every element passes the filtering condition.


Solution

The approach is straightforward: traverse the array using a loop, calling the provided filtering function for each element along with its index. If the function returns a truthy value (i.e., Boolean(value) evaluates to true), add that element to the resulting filtered array. This leverages a simple iterative loop and a temporary storage array, ensuring that we do not use any disallowed built-in filtering methods.


Code Solutions

# Define the filter function that takes an array and a filtering function.
def filter_array(arr, fn):
    # Initialize an empty list to store the filtered results.
    filtered_result = []
    # Iterate over each element of the array along with its index.
    for index, value in enumerate(arr):
        # Check if the filtering function returns a truthy value.
        if fn(value, index):
            # If truthy, append the value to the result list.
            filtered_result.append(value)
    # Return the filtered array.
    return filtered_result

# Example usage:
if __name__ == "__main__":
    # Define an example filtering function.
    def greater_than_10(n, i):
        return n > 10

    # Test the function with an example array.
    example_array = [0, 10, 20, 30]
    print(filter_array(example_array, greater_than_10))  # Expected output: [20, 30]
← Back to All Questions