2634. Filter Elements from Array LeetCode Solution

In this guide, you will get 2634. Filter Elements from Array LeetCode Solution with the best time and space complexity. The solution to Filter Elements from Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Filter Elements from Array solution in C++
  4. Filter Elements from Array solution in Java
  5. Filter Elements from Array solution in Python
  6. Additional Resources
2634. Filter Elements from Array LeetCode Solution image

Problem Statement of Filter Elements from Array

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
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. A truthy value is a value where Boolean(value) returns true.
Please solve it without the built-in Array.filter method.

Example 1:

Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
Output: [20,30]
Explanation:
const newArray = filter(arr, fn); // [20, 30]
The function filters out values that are not greater than 10
Example 2:

Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
Output: [1]
Explanation:
fn can also accept the index of each element
In this case, the function removes elements not at index 0

Example 3:

Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }
Output: [-2,0,1,2]
Explanation:
Falsey values such as 0 should be filtered out

Constraints:

0 <= arr.length <= 1000
-109 <= arr[i] <= 109

Complexity Analysis

  • Time Complexity: Google AdSense
  • Space Complexity: Google Analytics

2634. Filter Elements from Array LeetCode Solution in C++

type Fn = (n: number, i: number) => any;

function filter(arr: number[], fn: Fn): number[] {
  const ans: number[] = [];
  arr.forEach((a, index) => {
    if (fn(a, index)) {
      ans.push(a);
    }
  });
  return ans;
}
/* code provided by PROGIEZ */

2634. Filter Elements from Array LeetCode Solution in Java

N/A
// code provided by PROGIEZ

2634. Filter Elements from Array LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.