Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm - the time complexity of deletion in a unsorted array

Suppose there is a unsorted array A, and it contains an element x (x is the pointer of the element), and every element has a satellite variable k. So, we can get the following time complexity (for worst cases):

If we want to Search for a particular K, then it costs O(n).

if we want to Insert an element, then it costs O(1), because A just adds the element to the end.

What if we know x, then Delete it from the array A?

We have to Search for x.k first and get the index of x, then Delete x via its index in A, right?

So for Delete, it costs O(n) too, right?

thanks

like image 785
Jackson Tale Avatar asked Nov 28 '22 06:11

Jackson Tale


1 Answers

Finding the element with a given value is linear.

Since the array isn't sorted anyway, you can do the deletion itself in constant time. First swap the element you want to delete to the end of the array, then reduce the array size by one element.

like image 163
Jerry Coffin Avatar answered Dec 15 '22 07:12

Jerry Coffin