ericdrowell/BigOCheatSheet

Isn't insertion in a (unsorted) dynamic array O(1) instead of O(n)?

pakmans opened this issue · 3 comments

Isn't insertion in a (unsorted) dynamic array O(1) instead of O(n)?

@pakmans Yes, it is!
The actual table should be like this:

+----------------------+----------+------------+----------+--------------+
|                      |  Insert  |   Delete   |  Search  | Space Usage  |
+----------------------+----------+------------+----------+--------------+
| Unsorted array       | O(1)     | O(1)       | O(n)     | O(n)         |
| Value-indexed array  | O(1)     | O(1)       | O(1)     | O(n)         |
| Sorted array         | O(n)     | O(n)       | O(log n) | O(n)         |
| Unsorted linked list | O(1)*    | O(1)*      | O(n)     | O(n)         |
| Sorted linked list   | O(n)*    | O(1)*      | O(n)     | O(n)         |
| Balanced binary tree | O(log n) | O(log n)   | O(log n) | O(n)         |
| Heap                 | O(log n) | O(log n)** | O(n)     | O(n)         |
| Hash table           | O(1)     | O(1)       | O(1)     | O(n)         |
+----------------------+----------+------------+----------+--------------+

 * The cost to add or delete an element into a known location in the list (i.e. if you have an iterator to the location) is O(1). If you don't know the location, then you need to traverse the list to the location of deletion/insertion, which takes O(n) time. 
** The deletion cost is O(log n) for the minimum or maximum, O(n) for an arbitrary element.

@pakmans It is however if the array is full then we would need to create a larger array of double size and copy all the elements to it which would take O(n) time. So if I am not wrong then the best case for insertion in an unsorted array should be O(1) and worst case O(n).

@SManral depending on how you grow the array, you can turn the insertion worst case from O(n) into amortized O(1).