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