#2634

Filter Elements from Array

Easy
ArrayFunctional Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution is similar to the brute force approach but focuses on clarity and efficiency. It uses a single loop to filter elements based on the provided function, ensuring we only traverse the array once.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty array called filteredArr.
  2. 2Step 2: Loop through each element of arr using its index.
  3. 3Step 3: For each element, call the function fn with the element and its index.
  4. 4Step 4: If the result of fn is truthy, add the element to filteredArr.
  5. 5Step 5: Return filteredArr after the loop.
solution.py2 lines
1def filter(arr, fn):
2    return [arr[i] for i in range(len(arr)) if fn(arr[i], i)]

Complexity note: The time complexity remains O(n) as we still traverse the array once. The space complexity is O(n) for the new filtered array.

  • 1Understanding truthy and falsy values is crucial for filtering.
  • 2Using a single loop is efficient for this problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.