What happens when (n+1)th element inserted in a dynamic array of size n?
Lets see the memory allocation in the array, when an array of size n is declared a certain continuous block of memory is allocated for that.
for example when an array of size 5 declared each unit occupying 2 bytes and memory continuous block if started from 1000 then allocated memory is from address 1000 to 1010.
Here a continuous memory after allocated the next memory is used by other variables or any other data. so next 1011 space is occupied. when we try to insert a new element in that array. the CPU finds a memory that is double the size of the present array’s memory.
previous array: size = 5 memory = 10 bytes
present array: size = 10 a memory = 20 bytes
we can't say for sure its 2x size but its around the between 1.5x to 2x.
After Finding a new memory of generally 2x size and points the same variable at the newly formed memory space. Now it takes all the elements from the previous memory location and inserts them in the new memory location[ It means it inserts all the n elements from the previous array] and inserts them in the new array.
After the n+1 element is inserted in the (n+1)th space of the newly formed array.
Time taken for insertion of(n+1)th element is:
1.Finding memory space
2.insert all the previous n elements takes time of O(n)
3.n+1 element insertion takes O(1).
Totally for inserting n+1 element in the dynamic array of size n is n+1
For example, we have an array A[] of size 5:
inserting 0th element A[0]=10 → 1
inserting 1st element A[1]=20 → 1
inserting 2nd element A[2]=30 → 1
inserting 3rd element A[3]=40 → 1
inserting 4th element A[4]=50 → 1
so for a total of five elements insertion time taken is O(5).
Now if we try to insert 60 into an array then the CPU finds 2x of present size and changes the reference address of A[] of size 10 to the new address.
After it inserts all the elements 10,20,30,40,50 in the new array it takes O(5) time. Now it inserts 60 at A[5] and the time taken here is O(5) +O(1) because for inserting 60 CPU has to find new memory, insert old ones, and 60.
But from hereafter up to A[9], the insertion of new elements takes O(1).
This is the same for every (n+1)th element when inserted into an array of size n.
So whenever we try to insert (n+1)th element in an array of size n. A new array space is formed in memory which is 1.5x to 2x size of the previous array and inserts a new element in that. previous memory space is destroyed.