#2634
Filter Elements from Array
EasyArrayFunctional Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal 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- 1Step 1: Initialize an empty array called filteredArr.
- 2Step 2: Loop through each element of arr using its index.
- 3Step 3: For each element, call the function fn with the element and its index.
- 4Step 4: If the result of fn is truthy, add the element to filteredArr.
- 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.