VOOZH about

URL: https://www.geeksforgeeks.org/dsa/delete-an-element-from-a-given-position-in-an-array/

⇱ Delete an Element from a Given Position in an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Delete an Element from a Given Position in an Array

Last Updated : 8 Nov, 2024

Given an array of integers, the task is to delete an element from a given position in the array.

Examples:

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

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

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

[Approach 1] Using Built-In Methods

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


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

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

[Approach 2] Using Custom Method

The idea is to shift all the elements occurring after the given position, one index to the left and reduce the size of the array by 1.


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

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

Comment
Article Tags:
Article Tags: