LeetCode 2634: Filter Elements from Array Solution
Master LeetCode problem 2634 (Filter Elements from Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2634. Filter Elements from Array
Problem Explanation
Explanation
To solve this problem, we will iterate through the input array arr and apply the filtering function fn to each element. If the result of applying fn is truthy, we add the element to the filteredArr. We will implement this algorithm in a straightforward manner without using the built-in filter method.
- Time complexity: O(n), where n is the number of elements in the input array
arr. - Space complexity: O(n), the space used by the
filteredArr.
Solution Code
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<Integer> filter(int[] arr, FilterFunction fn) {
List<Integer> filteredArr = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
if (fn.filter(arr[i], i)) {
filteredArr.add(arr[i]);
}
}
return filteredArr;
}
}
interface FilterFunction {
boolean filter(int n, int index);
}Try It Yourself
Loading code editor...
Frequently Asked Questions
How to solve LeetCode 2634 (Filter Elements from Array)?
This page provides optimized solutions for LeetCode problem 2634 (Filter Elements from Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2634 (Filter Elements from Array)?
The time complexity for LeetCode 2634 (Filter Elements from Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2634 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2634 in Java, C++, or Python.