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