VOOZH about

URL: https://www.geeksforgeeks.org/dsa/insert-element-at-the-beginning-of-an-array/

⇱ Insert Element at the Beginning of an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Insert Element at the Beginning of an Array

Last Updated : 7 Nov, 2024

Given an array of integers, the task is to insert an element at the beginning of the array.

Examples:

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

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

[Approach 1] Using Built-In Methods

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


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

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

[Approach 2] Using Custom Method

To insert an element at the beginning of an array, first shift all the elements of the array to the right by 1 index and after shifting insert the new element at 0th position.


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

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

Comment
Article Tags:
Article Tags: