Remove elements from an array according to a filtering rule and return the remaining elements in order.
Filter Array
gfgFilter 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
nspace-separated integersnums[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
- Preserve the original order of elements not removed.
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.