Last Updated: 31 Mar, 2025

Remove All Occurrences

Easy
Asked in company
DP World

Problem statement

You are given an array 'A' of length 'N' and an element 'E'.


Return a new array containing all elements of 'A' except for all occurrences of 'E'. The order of the remaining elements should be preserved.


For Example :
Let 'N' = 6, 'A' = [1, 2, 2, 3, 4, 2], 'E' = 2.
The resulting array after removing all occurrences of 2 is [1, 3, 4].
Input Format :
The first line contains two integers, 'N' and 'E', separated by a space.
The second line contains 'N' integers representing the elements of the array 'A', separated by spaces.
Output Format :
Return the modified array with all occurrences of 'E' removed.
Note :
You don’t need to print anything. Just implement the given function.
Constraints :
1 <= 'N' <= 10^5
-10^9 <= elements of 'A', 'E' <= 10^9

Time Limit: 1 sec

Approaches

01 Approach

Approach:

  • Initialize an empty array to store the result.
  • Iterate through the input array.
  • For each element in the input array, check if it is equal to the element to be removed.
  • If it is not equal, add it to the result array.
  • Finally, return the result array.

Algorithm:

  • Initialize an empty array 'result'.
  • Iterate using index 'i' from 0 to 'N - 1' :
    • If ( 'A[ i ]' is not equal to 'E' ) :
      • Append 'A[ i ]' to 'result'.
  • Return 'result'.