![]() |
VOOZH | about |
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]
We will use library methods like erase() in C++, remove() in Java and Python, Remove() in C# and splice() in JavaScript.
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)
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.
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)