Remove All Occurrences

Easy
0/40
1 upvote
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].
Detailed explanation ( Input/output format, Notes, Images )
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
Sample Input 1 :
5 3
1 3 2 3 4
Sample Output 1 :
1 2 4
Explanation of sample input 1 :
The given array is [1, 3, 2, 3, 4] and the element to remove is 3.
We iterate through the array. The first element is 1, which is not 3, so we keep it.
The second element is 3, which is equal to the element we want to remove, so we discard it.
The third element is 2, which is not 3, so we keep it.
The fourth element is 3, which is equal to the element we want to remove, so we discard it.
The fifth element is 4, which is not 3, so we keep it.
Thus, the resulting array is [1, 2, 4].
Sample Input 2 :
4 4
1 2 3 5
Sample Output 2 :
1 2 3 5
Hint

Consider building a new array containing only the elements that are not equal to the element to be removed.

Approaches (1)
Implementation

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'.
Time Complexity

O(N), where 'N' is the number of elements in the input array 'A'.

We iterate through each element of the input array 'A' once. Thus, the overall time complexity is of the order O(N).

Space Complexity

O(N), where 'N' is the number of elements in the input array 'A' in the worst case (when no elements are equal to 'E').

In the worst-case scenario, where no elements in the input array 'A' are equal to 'E', the 'result' array will have the same number of elements as 'A'. Thus, the overall space complexity is of the order O(N).

Code Solution
(100% EXP penalty)
Remove All Occurrences
Full screen
Console