Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Filter Elements From Array

Remove elements from an array according to a filtering rule and return the remaining elements in order.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Filter Array

gfg
Problem Statement

Filter Elements From Array

You are given an integer array nums and a value x.

Create and return a new array containing all elements of nums except those that should be filtered out according to the rule below:

  • Remove every element equal to x.
  • Keep all other elements in their original relative order.

Your task is to implement the filtering operation efficiently.

Notes

  • The original array should not be reordered.
  • If no elements need to be removed, return the array unchanged.
  • If all elements are removed, return an empty array.

Input Format

  • The first line contains an integer n, the number of elements.
  • The second line contains n space-separated integers nums[i].
  • The third line contains an integer x, the value to remove.

Output Format

Return the filtered array as a list of integers in the same relative order as the input.

Constraints

  • 0n1050 \le n \le 10^5
  • 109nums[i],x109-10^9 \le nums[i], x \le 10^9
  • Preserve the original order of elements not removed.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1, 2, 3, 2, 4], x = 2

Output

[1, 3, 4]

Explanation

All occurrences of 2 are removed, and the remaining elements stay in their original order.

Example 2

Input

nums = [5, 5, 5], x = 5

Output

[]

Explanation

Every element matches the filter value, so the result is empty.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.