VOOZH about

URL: https://www.geeksforgeeks.org/dsa/delete-first-occurrence-of-given-element-from-an-array/

⇱ Delete First Occurrence of Given Element from an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Delete First Occurrence of Given Element from an Array

Last Updated : 9 Nov, 2024

Given an array of integers, the task is to delete a given element from the array. If there are multiple occurrences of the element, we need to remove only its first occurrence.

Examples:

Input: arr[] = [10, 20, 30, 40], ele = 20
Output: [10, 30, 40]

Input: arr[] = [10, 20, 30, 40], ele = 25
Output: [10, 20, 30, 40]

Input: arr[] = [10, 20, 20, 20 30], ele = 20
Output: [10, 20, 20, 30]

[Approach 1] Using Built-In Methods

We will use library methods like erase() in C++, remove() in Java and Python, Remove() in C# and splice() in JavaScript.


Output
Array before deletion
10 20 20 20 30 
Array after deletion
10 20 20 30 

Time Complexity: O(n), where n is the size of input array.
Auxiliary Space: O(1)

[Approach 2] Using Custom Methods

The idea is to iterate over all the elements of the array and as soon as we encounter the element to be deleted, shift all the elements occurring to the right of the element, one position to the left.


Output
Array before deletion
10 20 20 20 30 
Array after deletion
10 20 20 30 

Time Complexity: O(n), where n is the size of input array.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: