VOOZH about

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

⇱ Insert Element at a Given Position in an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Insert Element at a Given Position in an Array

Last Updated : 7 Nov, 2024

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

Examples:

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

Input: arr[] = [], pos = 1, ele = 20
Output: [20]

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

[Approach 1] Using Built-In Methods

We will use library methods like insert() in C++, Python and C#, add() in Java and splice() in JavaScript.


Output
Array before insertion
10 20 30 40 
Array after insertion
10 50 20 30 40 

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

[Approach 2] Using Custom Method

To add an element at a given position in an array, shift all the elements from that position one index to the right, and after shifting insert the new element at the required position.


Output
Array before insertion
10 20 30 40 
Array after insertion
10 50 20 30 40 

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

Comment
Article Tags:
Article Tags: