Why insert/delete operations are slow in arrays

If you need to repeatedly perform insert and/or delete operations, the array should not be the choice of your data structure, because it is slow. The reason why insertion and deletion are slow is because of the shifting.

When you insert an element, you must shift all the elements to the right to create a space for that new element to be inserted, O(n).

Insertion example:

# insert 3 at index 3

[0][1][2][4][5][_]  # original

[0][1][2][_][4][5]  # shift every elements from index 3
[0][1][2][3][4][5]

Deletion example:

# delete index 3
[0][1][2][3][4][5] # original

[0][1][2][_][4][5] # index 3 removed; shift everything to fill in the gap
[0][1][2][4][5][_]

The only exception would be inserting at the end of the array, Ω(1).

Backlinks: