VOOZH about

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

⇱ Insert Element at the End of an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Insert Element at the End of an Array

Last Updated : 7 Nov, 2024

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

Examples:

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

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

[Approach 1] Using Built-In Methods

We will use library methods like push_back() in C++, add() in Java and C#, append() in Python and push() in JavaScript.


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

Time Complexity: O(1)
Auxiliary Space: O(1)

[Approach 2] Using Custom Method

To insert an element at the end of an array, we can simply add the new element at the nth index.


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

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: